微服务中的文件上传下载

文件上传下载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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 记一个程序员改bug的心路历程,以及具体的方法。方法论上可以模仿,具体的过程谨慎尝试,生命宝贵。 起因 2017年...
    ad110fe9ec46阅读 7,656评论 2 3
  • 文章图片上传不正常,如需文档,可联系微信:1017429387 目录 1 安装... 4 1.1 配置探针... ...
    Mrhappy_a7eb阅读 6,464评论 0 5
  • what 什么是架构? 架构就是分离关注点,各关注点相互隔离又相互配合,围绕一个共同的目的各司其职,评估选择最合适...
    Carden阅读 383评论 0 1
  • 今天的工作很忙碌,难得在银行排队的空隙反思了最近自己的糟糕生活状态。 我希望过得很舒适的生活,却被生活中扑面而来的...
    XF清凉君阅读 597评论 0 2