JAVA代码:
/**文件的上传和下载**/
@RestController
public class FileUpAndDownController {
// 上传文件
@PostMapping("/fileUpload")
public ResponseEntity<?> handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty");
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("src/main/resources/static/File" + File.separator + file.getOriginalFilename());
Files.write(path, bytes);
return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Could not upload the file: " + e.getMessage());
}
}
// 下载文件
@GetMapping("/fileDownload")
public ResponseEntity<?> downloadFile(HttpServletRequest request,@RequestParam("filename") String filename) {
try {
File file = new File("src/main/resources/static/File"+ File.separator +filename);
if (!file.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
filename=getFilename(request, filename);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=" + filename);
headers.setContentDispositionFormData("attachment",filename);
//定义以流的形式下载返回文件数据
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 这个东西很重要!!!!
// 如果不对文件名编码进行处理,会导致浏览器下载的文件不对版,还没扩展名
//根据浏览器的不同进行编码设置,返回编码后的文件名
private String getFilename(HttpServletRequest request, String filename)
throws Exception {
//IE不同版本User-Agent中出现的关键词
String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
//获取请求头代理信息
String userAgent = request.getHeader("User-Agent");
for (String keyWord : IEBrowserKeyWords) {
if (userAgent.contains(keyWord)) {
//IE内核浏览器,统一为UTF-8编码显示,并对转换的+进行更正
return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
}}
//火狐等其他浏览器统一为ISO-8859-1编码显示
return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
}
前端测试代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传下载</title>
</head>
<body>
<h1>文件上传</h1>
<form action="http://127.0.0.1:8080/fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file" required />
<button type="submit">上传</button>
</form>
<h2>下载文件</h2>
<form action="http://127.0.0.1:8080/fileDownload" method="get">
<input type="text" name="filename" placeholder="输入文件名" required />
<button type="submit">下载</button>
</form>
<script>
</script>
</body>
</html>