1. 文件上传
- 前端HTML
<form method="POST" action="/uploadFile" enctype="multipart/form-data">
<input type="file" id="file_input"name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
- 后端Controller
@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile file) {
if(file.isEmpty()) {
return;
}
String fileName = file.getOriginalFilename();
String filePath = "E:\\file\\";
File uploadFile = new File(filePath + fileName);
try {
if (!uploadFile.getParentFile().exists()) {
uploadFile.getParentFile().mkdirs();
}
file.transferTo(uploadFile);
LOGGER.info("上传文件成功");
} catch (IOException e) {
LOGGER.error("upload", e.getMessage());
}
}
2.文件下载
- 前端HTML
<a href="/download?filename="+data+"\">下载文件</a>
- 后端Controller
@RequestMapping(value="/download",method = RequestMethod.GET)
public void download(HttpServletRequest request, HttpServletResponse response){
String fileName = request.getParameter("filename");
File file=new File("E:\\file",fileName);
if(file.exists()){
try{
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
byte[]buffer=new byte[1024];
FileInputStream fis=null;
BufferedInputStream bis=null;
fis=new FileInputStream(file);
bis=new BufferedInputStream(fis);
OutputStream os=response.getOutputStream();
int i=bis.read(buffer);
while(i!=-1){
os.write(buffer,0,i);
i=bis.read(buffer);
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if(bis!=null){
bis.close();
}
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}