项目中用到简单的文件上传,记录一下,基于springBoot
@RequestMapping("/uploadFile")
@ResponseBody
public Map<String, Object> uploadFile (@RequestParam(value = "file") MultipartFile[] file, HttpServletRequest requestNew) {
log.info("批量上传文件开始==============");
Map<String, Object> result = new HashMap<>();
if (file == null || file.length == 0) {
result.put("msg", "上传失败,请先选择文件");
return result;
}
long start = System.currentTimeMillis();
try {
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
String dirName = sf.format(new Date());
String filePath = "你需要存储的服务器路径" + "/" + dirName;//excel生成的文件路径
File fileNew = new File(filePath);
if (!fileNew.exists()) {//判断目录是否存在
fileNew.mkdirs();
}
List<String> showUrls = new ArrayList<>();
for (MultipartFile singleFile : file) {
log.info("上传单个文件开始;文件名:"+ singleFile.getOriginalFilename());
long localStartTime = System.currentTimeMillis();
//生成文件名称已uuid命名
String uuid = UUID.randomUUID().toString().replaceAll("-","");
String fileNameOld = singleFile.getOriginalFilename();
String[] fileNameArr = fileNameOld.split("\\.");
String fileName = uuid + "." + fileNameArr[fileNameArr.length-1];
String filePathNew = filePath +"/" + fileName;
File newFile=new File(filePathNew);
singleFile.transferTo(newFile);
String basePath = requestNew.getScheme()+"://"+requestNew.getServerName();
log.info("上传单个文件结束,【" + fileNameOld +"】所耗时间:" + (System.currentTimeMillis() - localStartTime) + "ms");
String showUrl = basePath +"/production/" + dirName + "/" + fileName;
showUrls.add(showUrl);
}
result.put("showUrls", showUrls);
log.info("批量上传文件结束==============总耗时:" + (System.currentTimeMillis() - start ) +" ms");
} catch (Exception e) {
log.error("批量上传到服务器出错!", e);
}
return result;
}