文件上传与下载
一、文件上传
二、文件下载
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
package com.shao.controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@RestController
@RequestMapping("/file")
public class FileController {
@GetMapping("/download")
public void fileDownload(@RequestParam("filename") String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {
String basePath = "/tmp";
String downloadPath = basePath + File.separator + filename;
// 设置响应头
setAttachmentResponseHeader(response, filename);
// 写入数据
writeBytes(downloadPath, response.getOutputStream());
}
/**
* 设置文件下载的响应头
*
* @param response
* @param realFileName
* @throws UnsupportedEncodingException
*/
public void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
// setContentType方法用于设置响应的内容类型(Content-Type),告诉客户端发送的数据是什么类型的
// application/octet-stream
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
// 将文件名编码
String handlerPercentEncodeFilename = handlerPercentEncode(realFileName);
// 设置请求头
StringBuilder contentDispositionValue = new StringBuilder();
// attachment; filename=:这部分指定了文件的下载方式,attachment 表示文件作为附件下载,而不是在浏览器中直接打开
// filename:文件名字
contentDispositionValue.append("attachment; filename=")
// 编码后的文件名字,防止中文乱码
.append(handlerPercentEncodeFilename)
.append(";")
// filename*=utf-8:这是一个扩展的 filename 参数,它指定了文件名的编码方式和语言。utf-8
// 表示文件名采用 utf-8 编码。这个部分告诉客户端在下载文件时应该使用 utf-8 编码来解析文件名。
.append("filename*=")
.append("utf-8''")
// 需要解析的文件名称
.append(handlerPercentEncodeFilename);
// Content-Disposition
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue.toString());
}
/**
* 将文件名编码
*
* @param s 文件名
* @return 返回编码后的文件名
* @throws UnsupportedEncodingException
*/
private static String handlerPercentEncode(String s) throws UnsupportedEncodingException {
// 将文件编码
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);
// 将+替换为编码
return encode.replaceAll("\\+", "%20");
}
/**
* 写入
*
* @param filePath
* @param os
*/
public static void writeBytes(String filePath, OutputStream os) {
File file = new File(filePath);
try (FileInputStream is = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}