/**
* SpringBoot上传文件
* @param request
* @param path 文件路径
* @return
*/
public static Object uploadFile(HttpServletRequest request, String path){
MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
MultiValueMap<String, MultipartFile> filesMap = params.getMultiFileMap();
List<String> fileNames = new ArrayList<String>();
JSONObject json = new JSONObject();
boolean flag = true;
String errorFile = "";
ERROR:
for (String key: filesMap.keySet() ) {
List<MultipartFile> files = filesMap.get(key) ;
for (MultipartFile file :files
) {
String filename = file.getOriginalFilename();
String serverFileName = String.valueOf(new Date().getTime())+ (int)(Math.random()*100)
+filename.substring(filename.indexOf("."));

try {
filename = writeFile(file.getBytes(), path, serverFileName);
if(StringUtil.isNotEmpty(filename)){
//导入成功
fileNames.add(serverFileName);
}

} catch (Exception e) {
flag = false;
errorFile = filename;
break ERROR;
}
}
}
//如果有一个文件失败了,则返回false 已经成功的文件在fileNames(List<String>)内存储,失败的文件在errorFile(String)
json.put("success",flag);
json.put("fileNames",fileNames);
json.put("errorFile",errorFile);
return json;
}
posted on 2018-08-10 13:13  FeeCy  阅读(1442)  评论(0编辑  收藏  举报