java
// 文件上传和下载 multipartfile byte数组获取比特流
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "Please select a file to upload.";
}
try {
byte[] bytes = file.getBytes();
String uploadDir = "D:\\project\\wms\\web002-main\\wms001\\file_upload_download\\";
File uploadedFile = new File(uploadDir + file.getOriginalFilename());
file.transferTo(uploadedFile);
return "File uploaded successfully!";
} catch (IOException e) {
e.printStackTrace();
return "File upload failed!";
}
}
// 上传/下载的根目录(建议和上传接口保持一致,可从配置文件注入)
private static final String UPLOAD_DIR = "D:\\project\\wms\\web002-main\\wms001\\file_upload_download\\";
/**
* 文件下载接口
* @param fileName 要下载的文件名(前端传入,需和上传时的文件名一致)
* @return 响应体(包含文件流)
*/
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile(@RequestParam("fileName") String fileName) {
// 1. 构建要下载的文件完整路径
File downloadFile = new File(UPLOAD_DIR, fileName);
// 2. 校验文件是否存在
if (!downloadFile.exists()) {
// 返回 404 状态码 + 提示信息
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(("文件不存在:" + fileName .getBytes(StandardCharsets.UTF_8)).getBytes());
}
// 3. 读取文件字节流
try (InputStream inputStream = new FileInputStream(downloadFile)) {
// 读取文件到字节数组
byte[] fileBytes = new byte[(int) downloadFile.length()];
inputStream.read(fileBytes);
// 4. 设置响应头(关键:处理中文文件名、指定下载类型)
HttpHeaders headers = new HttpHeaders();
// 处理中文文件名乱码(URLEncoder 编码)
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace("+", "%20");
// 设置响应头:指定文件下载方式、文件名
headers.add("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
// 设置响应媒体类型(二进制流,支持所有文件类型)
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 设置文件大小
headers.setContentLength(fileBytes.length);
// 5. 返回响应(200 成功 + 响应头 + 文件字节流)
return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
// 返回 500 状态码 + 错误信息
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(("文件读取失败:" + e.getMessage()).getBytes(StandardCharsets.UTF_8));
}
}
yml配置
XML
server:
port: 8090
spring:
datasource:
url: jdbc:mysql://localhost:3306/wms
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
servlet:
multipart:
max-file-size: 10MB # 单个文件的最大大小
max-request-size: 10MB # 单次请求的总文件大小上限