一、Spring Boot下载文件到本地硬盘
在Spring Boot中,我们可以通过以下代码实现将一个文件下载到本地硬盘中:
@GetMapping("/download")
public ResponseEntity<FileSystemResource> download(HttpServletRequest request) throws IOException {
String fileName = "file.txt";
String filePath = "path/to/file/" + fileName;
FileSystemResource fileSystemResource = new FileSystemResource(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename=" + fileName);
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok().headers(headers).contentLength(fileSystemResource.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream")).body(fileSystemResource);
}
我们可以从请求中得到文件名,然后通过FileSystemResource获取文件的真实路径。
使用ResponseEntity将文件的内容输出到响应体中,实现文件下载到本地硬盘。同时通过添加相关的响应头信息来告诉浏览器将这个响应当做一个文件下载。
二、Spring Boot FTP下载文件
如果要实现从FTP服务器下载文件,我们可以使用Apache Commons Net库
首先添加maven依赖:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
然后通过以下代码实现从FTP服务器下载文件:
@GetMapping("/ftpdownload")
public String ftpDownload(HttpServletRequest request) throws IOException {
String server = "FTP服务器地址";
int port = 21;
String user = "用户名";
String password = "密码";
String remoteFilePath = "远程文件路径";
String localFilePath = "本地文件路径";
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(user, password);
InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
OutputStream outputStream = new FileOutputStream(localFilePath);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream.write(bytesArray, 0, bytesRead);
}
boolean success = ftpClient.completePendingCommand();
inputStream.close();
outputStream.close();
ftpClient.logout();
ftpClient.disconnect();
if (success) {
return "下载成功";
} else {
return "下载失败";
}
}
使用FTPClient连接到FTP服务器,并通过retrieveFileStream方法获取文件的输入流。
然后使用FileOutputStream将输入流写入到本地文件中。
三、Spring Boot文件上传下载功能
我们可以通过Spring Boot的MultipartFile来实现文件的上传,而下载则可以参考第一部分的做法。
以下代码实现了文件上传和下载的完整功能:
@GetMapping("/download")
public ResponseEntity<FileSystemResource> download(HttpServletRequest request) throws IOException {
...
}
@PostMapping("/upload")
public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String filePath = "path/to/file/" + fileName;
file.transferTo(new File(filePath));
return "上传成功";
}
文件上传使用@RequestParam注解获取文件,然后通过transferTo方法将文件写入到指定的路径中。
文件下载使用和第一部分中的代码一样的方式。
四、Spring Boot浏览器下载文件
如果需要将文件直接显示在浏览器中,而不是下载到本地硬盘,我们可以对第一部分中的代码进行修改:
@GetMapping("/display")
public ResponseEntity<FileSystemResource> display(HttpServletRequest request) throws IOException {
String fileName = "file.txt";
String filePath = "path/to/file/" + fileName;
FileSystemResource fileSystemResource = new FileSystemResource(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "inline; filename=" + fileName);
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok().headers(headers).contentLength(fileSystemResource.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream")).body(fileSystemResource);
}
将Content-Disposition响应头的attachment改为inline即可直接在浏览器中显示文件内容。
五、Spring Boot下载文件到本地目录
如果需要将文件下载到指定的本地目录中,我们可以通过以下代码实现:
@GetMapping("/folder")
public void folder(HttpServletRequest request, HttpServletResponse response) throws IOException {
String fileName = "file.txt";
String filePath = "path/to/file/" + fileName;
File file = new File(filePath);
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
FileInputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream.write(bytesArray, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
在这里,我们使用HttpServletResponse的getOutputStream方法获取输出流,然后将文件的内容写入到输出流中。
六、Spring Boot批量下载文件
最后,如果需要实现批量下载文件的功能,可以通过以下代码实现:
@GetMapping("/batch")
public void batch(HttpServletRequest request, HttpServletResponse response) throws IOException {
String[] fileNames = {"file1.txt", "file2.txt"};
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
for (String fileName : fileNames) {
String filePath = "path/to/file/" + fileName;
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
zipOut.write(bytesArray, 0, bytesRead);
}
inputStream.close();
}
zipOut.finish();
}
在这里,我们首先将多个文件名存放在一个数组中,然后使用ZipOutputStream将这些文件压缩为一个压缩包。
在输出响应体时,使用response的getOutputStream方法获取输出流并将压缩包写入到流中。
总结
本文详细介绍了在Spring Boot中实现文件下载的多个方面,包括下载到本地硬盘中、从FTP服务器下载文件、文件上传下载功能、浏览器下载文件、下载文件到本地目录和批量下载文件。
通过这些方法,我们可以实现非常灵活、实用的文件下载功能,便于我们在开发中实现各种各样的需求。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/248504.html
微信扫一扫
支付宝扫一扫