1.文件上传配置
spring:
servlet:
multipart:
max-file-size: 20MB
max-request-size: 10MB
2.前端写法
<form action="URL" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传</button>
</form>
3.后端实现单文件上传
/**
* 实现文件上传
* */
@RequestMapping("fileUpload")
@ResponseBody
public String fileUpload(@RequestParam("fileName") MultipartFile file){
if(file.isEmpty()){
return "false";
}
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
String path = "C:/test" ;
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest); //保存文件
return "true";
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
4.后端实现多文件上传
/**
* 实现多文件上传
* */
@RequestMapping(value="multifileUpload",method=RequestMethod.POST)
/**public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files) */
public @ResponseBody String multifileUpload(HttpServletRequest request){
List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
if(files.isEmpty()){
return "false";
}
String path = "F:/test" ;
for(MultipartFile file:files){
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
if(file.isEmpty()){
return "false";
}else{
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
}
return "true";
}
}
5.后端实现文件下载
@RequestMapping("/download")
public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
String filename="2.xlsx";
String filePath = "D:/download" ;
File file = new File(filePath + "/" + filename);
if(file.exists()){ //判断文件父目录是否存在
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename,"UTF-8"));
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("----------file download---" + filename);
try {
bis.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
网友评论