上传写法:通过前端传递参数还可实现多路径存储不同的文件
public String upload(List<MultipartFile> files,String clueCode,String path) {
UserVo userVo = uaaFeignService.selectUser().getData();
String uploadPath = "";
if (files!=null&&files.size()>0){
List<File> fileList = new ArrayList<>();
for (MultipartFile file : files) {
if (file != null &&file.getOriginalFilename()!=null) {
//linux上获取到的是JAR包路径,window获取到的是src同级路径
String systemPath = System.getProperty("user.dir");
log.error("user.dir方式获取的路径:"+systemPath);
File fileTemp = new File(systemPath, clueCode);
File fileUpload = new File(fileTemp, path);
//交办路径由jar路径+线索code+部门ID组成,因为要进行单位权限区分
if ("assign".equals(path)){
fileUpload = new File(fileUpload,userVo.getDepartCode());
}
uploadPath = fileUpload.getPath();
if (!fileUpload.exists()){
boolean mkdirs = fileUpload.mkdirs();
if (!mkdirs){
throw new RuntimeException("创建文件夹失败");
}
}
fileUpload = new File(fileUpload, file.getOriginalFilename());
if (fileUpload.exists()) {
//对上传的同名文件进行覆盖操作
boolean delete = fileUpload.delete();
if (!delete){
throw new RuntimeException("存在同名文件("+file.getOriginalFilename()+")并无法覆盖,请联系管理员!");
}
}
fileList.add(fileUpload);
try {
file.transferTo(fileUpload);
} catch (IOException e) {
if (fileList.size()>0){
for (File fileDelete : fileList) {
boolean delete = fileDelete.delete();
if (!delete){
throw new RuntimeException("本次上传失败,同时回滚数据失败,附件可能存在赃数据,如需删除联系管理员");
}
}
}
throw new RuntimeException("上传文件失败:" + e.toString());
}
}
}
}
return uploadPath;
}
下载写法:通过前端传递的文件存储路径和文件名来下载文件
public void download(String filePath, String fileName, HttpServletResponse response)throws IOException {
File file=new File(filePath,fileName);
if (file.isFile()){
response.setContentType("application/msword");//msword可以随便设置,别和当前项目别的下载冲突接口
response.setCharacterEncoding("UTF-8");
String encode = URLEncoder.encode(fileName, "UTF-8");//这是文件名,这样处理是解决乱码
response.addHeader("Content-Disposition", "attachment;filename=\"" + encode +"\"");
response.flushBuffer();
OutputStream outputStream = response.getOutputStream();
//输出文件
InputStream inputStream = new FileInputStream(file);
IOUtils.copy(inputStream, outputStream);
//关闭流
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}else {
throw new RuntimeException("文件不存在");
}
}
删除文件:通过前端传递的文件存储路径和文件名来删除文件
public void deleteAssignAnnex(String filePath, String fileName) {
File fileDelete = new File(filePath,fileName);
boolean delete = fileDelete.delete();
if (!delete){
throw new RuntimeException("删除失败,请联系管理员");
}
}