新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

springboot怎样下载服务器上的文件,springboot如何下载

发布时间:2023-09-18 08:49:29

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

要下载服务器上的文件,可使用Spring Boot中的`RestTemplate`类来发送HTTP GET要求并获得文件内容。以下是一个示例代码:
```java
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要求,并设置要求头中的`Accept`为`application/octet-stream`,以告知服务器我们需要下载二进制文件。然后,我们将获得到的文件内容保存到本地文件中。
请注意,上述代码中的`fileUrl`和`savePath`需要根据实际情况进行修改。另外,还需要确保你的Spring Boot利用程序有足够的权限来访问服务器上的文件。