前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="file/upload2">
<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
<a href="/file/download">文件下载</a>
</body>
</html>
文件上传后端代码
@PostMapping(value = "/upload2")
public String upload2(MultipartFile file) throws InterruptedException, IOException {
String result = null;
String path = filePath + file.getOriginalFilename();
File targetFile = new File(path);
file.transferTo(targetFile);
return result;
}
文件下载后端代码
@RequestMapping("/download")
public void downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
String filename = "test_download.txt";
File file = new File(filePath + "/" + filename);
if (file.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = null;
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);) {
os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
demo地址:fileupload: fileupload