前言
最近一个项目使用到了文件下载,写篇博客记录
basePath为父目录路径(?)
上传
/**
* 文件上传
* @param files
* @return
*/
@PostMapping(value = "/uploadFile")
public ReturnMsg upload(@RequestParam(value = "file", required = false) MultipartFile[] files){
if (files == null || files.length == 0)
return new ReturnMsg("200","操作成功",null);
StringBuilder fileName = new StringBuilder();
List<String> returnFileNames = new ArrayList<>(); //返回给前端已经上传成功的文件集合
Map<String,String> map=new HashMap<>();
for (MultipartFile file: files) {
if(file.isEmpty())
continue;
String originalFilename = file.getOriginalFilename(); //上传文件名
int i = originalFilename.lastIndexOf(".");
String serverFileName = System.currentTimeMillis()+"_"+originalFilename; //存储到服务器中的文件名
fileName.append(serverFileName).append(","); //储存到数据库文件名拼接串
//filePath.append(basePath).append(serverFileName).append(","); //存储到数据库文件路径拼接串
try {
File file1 = new File(basePath);
if (!file1.exists())
file1.mkdirs();
Path path = Paths.get(basePath, serverFileName);
Files.copy(file.getInputStream(),path);
} catch (IOException e) {
e.printStackTrace();
return new ReturnMsg("400","文件上传失败,请重试");
}
returnFileNames.add(serverFileName); //将成功上传的文件名添加到list中
map.put("fileName",originalFilename);
map.put("filePath",serverFileName);
}
return new ReturnMsg("200","上传成功",map);
}
下载
/**
* 文件下载
* @param fileName
* @param response
* @return
*/
@GetMapping(value = "/file/{fileName:.+}")
public ReturnMsg downLoadFile(@PathVariable String fileName, HttpServletResponse response){
if (ValidUtil.checkStr(fileName))
return new ReturnMsg("400","请指定需要下载的文件");
File file = new File(basePath, fileName);
//System.out.println(file.getPath());
if(!file.exists()||file.isDirectory())
return new ReturnMsg("400","文件不存在");
response.setHeader("Content-Disposition","attachment;filename"+fileName);
//response.setContentType("application/octet-stream");
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
ServletOutputStream outputStream = null;
byte[]buffer = new byte[1024];
try {
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
outputStream = response.getOutputStream();
int read = bufferedInputStream.read(buffer);
while (read!=-1){
outputStream.write(buffer,0,read);
read = bufferedInputStream.read(buffer);
}
outputStream.flush();
outputStream.close();
} catch (IOException e) {
return new ReturnMsg("400","文件下载失败");
}finally {
if(bufferedInputStream!=null){
try {
bufferedInputStream.close();
} catch (IOException e) {
System.out.println("文件流关闭失败");
}
}
if(fileInputStream!=null){
try {
fileInputStream.close();
} catch (IOException e) {
System.out.println("文件流关闭失败");
}
}
}
return new ReturnMsg("200","文件下载成功");
}
删除
/**
* 文件删除
* @param filePath
* @throws MyException
*/
@GetMapping("/deleteFile")
public ReturnMsg deleteFile(String filePath) throws MyException {
File file = new File(basePath,filePath);
System.out.println(file.getPath());
System.out.println(file.exists());
if(!file.exists()||file.isDirectory()){
// throw new MyException("该文件不存在");
return new ReturnMsg("400",filePath+",该文件不存在");
}
try{
//deleteOnExit删除不太好使换成下边的
//file.deleteOnExit();
file.delete();
}catch (Exception e){
throw new RuntimeException("删除失败"+e);
}
return new ReturnMsg("200","删除成功");
}
祝你幸福
送你一首歌:《With An Orchid》 Yanni
附图:禁毒电视剧《破冰行动》