将文件上传到服务器上的指定文件夹(可自定义)
uploadUrl 为指定上传文件路径 (/data/uploads/)
window 环境默认上传到D盘
返回json信息 上传成功时返回code 1上传失败时返回 code 0
public JSONObject uploadFileToLocal(HttpServletRequest request) {
JSONObject oject = new JSONObject();
oject.put("code", 0);
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//生成日期文件夹
LocalDate today = LocalDate.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String fileDir = today.format(fmt);
//生成文件上传路径
String ctxPath = uploadUrl + fileDir;
File file = new File(ctxPath);
if (!file.exists()) {
file.mkdirs();
}
String fileName = null;
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
MultipartFile mf = (MultipartFile) entity.getValue();
fileName = mf.getOriginalFilename();
String suffix = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : null;
//生成文件存储名
String newFileName = uuid + (suffix != null ? suffix : "");
File uploadFile = new File(ctxPath + File.separatorChar + newFileName);
try {
//上传文件
FileCopyUtils.copy(mf.getBytes(), uploadFile);
//组合返回信息
String url = "/"+fileDir+"/" + newFileName;
oject.put("fileName", fileName);
oject.put("fileUrl", url);
oject.put("code", 1);
log.info("文件路径:[{}] ", url);
} catch (IOException e) {
log.error("文件上传失败:[{}] ", fileName);
e.printStackTrace();
}
}
return oject;
}
上传成功返回json
{"isSuccess":1,"data":{"fileName":"aaaa.xlsx","code":1,"fileUrl":"/2021-01-05/0d807b278bbf49408440d32557261033.xlsx"},"msg":null}