美文网首页
微服务中的文件上传下载

微服务中的文件上传下载

作者: DimonHo | 来源:发表于2018-06-12 15:54 被阅读298次

    文件上传下载rest接口定义

    import cn.hutool.core.io.FileUtil;
    import cn.hutool.core.util.StrUtil;
    import cn.hutool.crypto.digest.DigestUtil;
    
    @Api(value = "文件controller", tags = {"文件上传下载接口"})
    @RestController
    @RequestMapping("/file")
    public class FileController{
    
        private static final String SAVE_PATH = System.getProperty("user.home");
        /**
         * 上传文件
         *
         * @param file
         * @return
         */
        @ApiOperation(value = "上传文件")
        @PostMapping("/upload")
        public String upload(@NotNull MultipartFile file) {
            //文件MD5值
            String md5File = DigestUtil.md5Hex(file.getInputStream());
            //文件后缀
            String extName = StrUtil.subAfter(file.getOriginalFilename(), ".", true);
            //文件如果不存在,则保存,否则直接返回文件的MD5名
            File localFile  = new File(SAVE_PATH, md5File)
            if (!FileUtil.exist(localFile)) {
                //创建一个新文件
                File attachFile = FileUtil.touch(SAVE_PATH, md5File);
                //将文件流写入文件中
                FileUtil.writeFromStream(file.getInputStream(), attachFile);
                return "文件上传成功"
            }
            return "文件已存在";
        }
    
    
    
        /**
         * 文献下载
         *
         * @return
         */
        @ApiOperation(value = "求助文件下载")
        @ApiImplicitParam(name = "fileName", value = "文件名", dataType = "String", paramType = "query")
        @GetMapping("/download")
        public ResponseEntity download(@RequestParam String fileName) {
            File file = new File(SAVE_PATH, fileName);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            //chrome浏览器下载文件可能出现:ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION,
            //产生原因:可能是因为文件名中带有英文半角逗号, 
            //解决办法:确保 filename 参数使用双引号包裹[1]
            headers.add("Content-Disposition", "attachment; filename=\"" + file.getName()+"\"");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(downloadModel.getDocFile().length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new FileSystemResource(file));
        }
    }
    

    restTemplat调用api上传

    public void uploadFile(@NotNull MultipartFile file){
            File newFile = FileUtil.writeFromStream(file.getInputStream(),"F:/upload/"+file.getOriginalFilename());
            FileSystemResource fs =new FileSystemResource(newFile);
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            //这里不能直接传参File或MultipartFile,需要用FileSystemResource包装一下 
            param.add("file",fs);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String,Object>> httpEntity = new HttpEntity<>(param,headers);
            ResponseEntity<String> responseEntity = new RestTemplate().exchange("http://cloud.test.hnlat.com/zuul/resources-server/file/upload", HttpMethod.POST, httpEntity,String.class);
            String fileName = responseEntity.getBody().toString();
    }
    

    附:
    [1]http://codeverge.com/embarcadero.delphi.intraweb/chrome-err_response_headers_multi/1061174

    相关文章

      网友评论

          本文标题:微服务中的文件上传下载

          本文链接:https://www.haomeiwen.com/subject/nialeftx.html