1、定义文件上传的路径(一般位于服务器某个文件夹,根据公司要求自定义)
2、Controller,注意:此处返回值类型为String,根据自己业务来改
@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "multipart/form-data; charset=utf-8")
@ApiOperation(httpMethod = "POST", value = "附件上传")
public String softwareList(@RequestParam("file") MultipartFile file, HttpServletRequest request,
HttpServletRequest response) {
UploadFile uploadFile = new UploadFile();
uploadFile.setFile(file);
ApiOutParamsInfo<UploadFileOut> apiOutParamsInfo = new ApiOutParamsInfo<>();
apiOutParamsInfo = fileUpload.appendFile(uploadFile);
return JSON.toJSONString(apiOutParamsInfo);
}
2、 文件上传实现类
@Value("${DEFAULTPATH}")
private String DEFAULTPATH;
@Value("${DEFAULTURL}")
private String DEFAULTURL;
public ApiOutParamsInfo appendFile(UploadFile uploadFile) {
MultipartFile file = uploadFile.getFile();
ApiOutParamsInfo apiOutParamsInfo = new ApiOutParamsInfo();
if (file != null && !file.isEmpty()) {
String fileName = file.getOriginalFilename();
String affixId = CommUtil.getUUID();
long time = System.currentTimeMillis();
String ftpPath = DEFAULTPATH+CommUtil.fetchSystemDate("yyyyMMdd") + "/" + time + "/" + fileName;
File dest = new File(ftpPath);
// 校验文件夹目录是否存在,不存在就创建一个目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest); // 保存文件
//将上传信息保存到数据库中
SysAffix sysAffix = new SysAffix();
sysAffix.setAffixId(affixId);
sysAffix.setAffixPath(ftpPath);
sysAffix.setAffixName(fileName);
sysAffix.setAffixUrl(DEFAULTURL+CommUtil.fetchSystemDate("yyyyMMdd") + "/" + time + "/" + fileName);
baseDao.save(sysAffix);
apiOutParamsInfo.setCode("0");
apiOutParamsInfo.setResult(sysAffix);
} catch (Exception e) {
e.printStackTrace();
apiOutParamsInfo.setCode("1");
apiOutParamsInfo.setResult(new SysAffix());
apiOutParamsInfo.setMsg("上传失败");
}
} else {
apiOutParamsInfo.setCode("1");
apiOutParamsInfo.setResult(new SysAffix());
apiOutParamsInfo.setMsg("上传文件为空");
}
return apiOutParamsInfo;
}