117.info
人生若只如初见

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 requestEntity = new RequestEntity<>(headers, HttpMethod.GET, URI.create(fileUrl));
ResponseEntity 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应用程序有足够的权限来访问服务器上的文件。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fe657AzsLBwZTBl0.html

推荐文章

  • 广州云主机租用要注意什么

    租用广州云主机时,需要注意以下几点: 价格:了解不同云主机提供商的定价和费用结构,确保选择适合自己需求和预算的云主机。 可用性和稳定性:选择具有高可用性...

  • 云主机登录流程是什么

    云主机登录流程通常包括以下步骤: 获取云主机的IP地址:首先需要知道云主机的IP地址,可以从云服务商的管理界面或者API中获取。 打开终端或命令提示符:在本地计...

  • eclipse多窗口显示怎么设置

    要在Eclipse中显示多个窗口,你可以按照以下步骤进行设置: 打开Eclipse,点击顶部菜单的“Window”选项。 在下拉菜单中选择“New Window”选项。 这样会在Eclip...

  • java中properties配置文件怎么使用

    在Java中,可以使用java.util.Properties类来读取和使用配置文件。
    首先,创建一个Properties对象并加载配置文件。可以使用Properties的load()方法来加载配...