springboot怎么下载服务器上的文件


要下载服务器上的文件,可以使用Spring Boot中的RestTemplate类来发送HTTP GET请求并获取文件内容。以下是一个示例代码:

import org.springframework.core.io.Resource;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpMethod;import org.springframework.http.MediaType;import org.springframework.http.RequestEntity;import org.springframework.http.ResponseEntity;import org.springframework.util.FileCopyUtils;import org.springframework.web.client.RestTemplate;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.net.URI;import java.nio.file.Files;import java.nio.file.Path;public class FileDownloader {public static void main(String[] args) throws IOException {String fileUrl = "http://example.com/file.pdf";String savePath = "/path/to/save/file.pdf";RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setAccept(MediaType.APPLICATION_OCTET_STREAM);RequestEntity<Object> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, URI.create(fileUrl));ResponseEntity<Resource> responseEntity = restTemplate.exchange(requestEntity, Resource.class);Resource resource = responseEntity.getBody();File file = new File(savePath);Files.createDirectories(file.getParentFile().toPath());try (FileOutputStream outputStream = new FileOutputStream(file)) {FileCopyUtils.copy(resource.getInputStream(), outputStream);}System.out.println("File downloaded successfully!");}}

在上述示例中,我们使用RestTemplate来发送HTTP GET请求,并设置请求头中的Acceptapplication/octet-stream,以告知服务器我们需要下载二进制文件。然后,我们将获取到的文件内容保存到本地文件中。

请注意,上述代码中的fileUrlsavePath需要根据实际情况进行修改。另外,还需要确保你的Spring Boot应用程序有足够的权限来访问服务器上的文件。


上一篇:如何修改云主机密码

下一篇:SQLite3.dll丢失怎么办


SpringBoot 服务器
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器