文件上传 下载

文件上传

controller

 1     public Object updateHeadPortrait(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws Exception{
 2         SysUser sysUser = userUtil.getSysUser(request);
 3         // 判断文件类型
 4         int fileType = FileTypeUtil.checkFileType(file);
 5         if (1 == fileType) {
 6             // 文件为空
 7             return RestResponse.buildError(ReturnCode.file_is_null);
 8         }
 9         String fileTypes = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."),file.getOriginalFilename().length());
10         if(!(".png").equals(fileTypes)&&!(".jpg").equals(fileTypes)){
11             return RestResponse.buildError(ReturnCode.file_type_error);
12         }
//上传文件
13 Map map = commonService.uploadImage(file); 14 15 return RestResponse.buildSuccess(); 16 }

impl

 1  public Map uploadImage(MultipartFile file) throws Exception {
 2         String tempPath = format.format(new Date()); //定义文件名
 3         File tempFile = new File(filePath+File.separator+tempPath);
 4         if(!tempFile.exists()){
 5             tempFile.mkdirs();
 6         }
 7         String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."),file.getOriginalFilename().length());//获取文件类型
 8         String filePaths = tempPath+"/"+ UUIDUtil.getUUID()+fileType; //文件保存位置
 9         File f = new File(filePath+File.separator+filePaths);
10         file.transferTo(f);
11         Map map = new HashMap();
12         map.put("path",filePaths);
13         return map;
14     }

下载

  @Override
    public void download(DocumentFileDto documentFileDto, HttpServletResponse response) throws Exception {
        ServletOutputStream out = null;
        FileInputStream ips = null;
        try {
            //获取图片存放路径
            String imgPath = filePath + File.separator + documentFileDto.getUrl();  //拼接下载路径
            ips = new FileInputStream(new File(imgPath));
            response.setContentType(documentFileDto.getFileType());
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Content-Type", "application/octet-stream");
       //下载时文件名中文乱码问题 配置如下能解决 response.setHeader(
"Content-Disposition", "attachment;fileName=" + new String(documentFileDto.getFileName().getBytes(), "iso-8859-1")+documentFileDto.getFileType()); out = response.getOutputStream(); //读取文件流 int len = 0; byte[] buffer = new byte[1024 * 10]; while ((len = ips.read(buffer)) != -1){ out.write(buffer,0,len); } out.flush(); }catch (Exception e){ e.printStackTrace(); }finally { out.close(); ips.close(); } }
原文地址:https://www.cnblogs.com/huanglp/p/12901646.html