代码如下:
package com.ece.manager.web.file;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
*
* @author xxs
* @date 2020年9月8日
*/
@RestController
@ResponseBody
@RequestMapping("/upload")
public class UploadFileController {
@RequestMapping("/fileUpload") // 等价于 @RequestMapping(value = "/upload", method = RequestMethod.POST)
public List<String> fileUpload(HttpServletRequest req, @RequestParam("file") MultipartFile[] files) {
List<String> pathStrs = new ArrayList<String>();
if(files.length > 0){
//循环多次上传多个文件
for (MultipartFile file : files) {
if(!file.isEmpty()){
//1. 接收上传的文件
String realPathDir = req.getSession().getServletContext().getRealPath("/");
String path ="static/image/upload/jpg/"+(new Date()).getTime()+".jpg";
System.out.println("图片上传路径:"+realPathDir+path);
try {
File destFile = new File(realPathDir+path);
destFile.getParentFile().mkdirs();
//把浏览器上传的文件复制到希望的位置
file.transferTo(destFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println( "上传失败," + e.getMessage());
continue;
} catch (IOException e) {
e.printStackTrace();
System.out.println( "上传失败," + e.getMessage());
continue;
}
pathStrs.add(path);
}
}
}
return pathStrs;
}
}