美文网首页
OpenFeign 文件上传下载

OpenFeign 文件上传下载

作者: 我叫钱多多_ | 来源:发表于2020-01-09 16:26 被阅读0次

    由于自己也是在网上几经一番折腾才找到部分博客并加以修改实现; 话不多说直接上代码;

    1.1 文件上传之服务端代码(在此处以服务端内部上传OSS为例)

         @PostMapping(value = "upload")
        public BaseResult<String> test(MultipartFile file) {
            String downloadUrl = fileService.upload(file);
            Preconditions.checkArgument(StringUtils.isNotEmpty(downloadUrl), UPLOAD_FILE_ERROR);
            return BaseResult.generateSuccessRestlt(downloadUrl);
        }
      
          @Override
        public String upload(MultipartFile file) {
            String filename = file.getOriginalFilename();
            try (InputStream inputStream = file.getInputStream()) {
                PutObjectRequest putObjectRequest = new PutObjectRequest(fileConfig.getBucketName(),
                    filename, inputStream);
                ossClient.putObject(putObjectRequest);
            } catch (IOException e) {
                log.error("filename:[{}],获取文件输入流错误!", filename, e);
                return null;
            } catch (OSSException | ClientException e) {
                log.info("上传文件失败filename:[{}]", filename, e);
                return null;
            }
            return filename;
        }
    

    1.2 文件下载之服务端代码

          @GetMapping(value = "download")
        public void down(@RequestParam(value = "filename") String filename,
            HttpServletResponse response) {
            fileService.download(filename, response);
        }
    
          @Override
        public void download(String filepath, HttpServletResponse response) {
            response
                .setContentType("application/x-download;charset=" + Charsets.UTF_8.displayName());
            response.addHeader("Content-Disposition",
                "attachment;filename=" + this.reWriteChinese(filepath));
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject;
            try {
                ossObject = ossClient.getObject(fileConfig.getBucketName(), filepath);
            } catch (OSSException | ClientException e) {
                log.error("获取OSS文件连接异常,filePath:[{}]", filepath, e);
                return;
            }
    
            try (OutputStream outputStream = response.getOutputStream();
                InputStream inputStream = ossObject.getObjectContent()) {
                IOUtils.copy(inputStream, outputStream);
                outputStream.flush();
            } catch (IOException e) {
                log.error("下载文件异常 filepath:[{}]", filepath, e);
            }
        }
    

    1.3 文件上传和下载FeignClient调用方代码

      /*
     * Copyright (c) 2020 daguimu.geek@gmail.com
     * All rights reserved.
     *
     */
    package com.dagm.api.feignclient;
    
    import feign.Response;
    import feign.codec.Encoder;
    import feign.form.spring.SpringFormEncoder;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.context.annotation.Bean;
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RequestPart;
    import org.springframework.web.multipart.MultipartFile;
    
    /**
     * @author Guimu
     * @date 2020/01/08
     */
    @FeignClient(value = "file-service", configuration = FileFeign.MultipartSupportConfig.class)
    public interface FileFeign {
    
        /**
         * 调用feign 对文件进行上传
         *
         * @param file 待上传的文件
         * @return com.dagm.shorter.res.BaseResult<java.lang.String>
         * @author Guimu
         * @date 2020/1/8
         */
        @PostMapping(value = "/inner/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        BaseResult<String> upload(@RequestPart("file") MultipartFile file);
    
        /**
         * 文件下载
         *
         * @return feign.Response
         * @author Guimu
         * @date 2020/1/8
         */
        @GetMapping(value = "/inner/download")
        Response download(@RequestParam("filename") String filename);
    
        class MultipartSupportConfig {
    
            @Bean
            public Encoder feignFormEncoder() {
                return new SpringFormEncoder();
            }
        }
    }
    

    1.4 tip:

    1. 文件的上传下载服务端代码, 和一般的上传下载一样:
      OpenFeign 文件上传需要配置Encoder, 我这里用的是feign-form; 也可以选择其他的;
      feign-form 版本对应 3.5版本之后的对应OpenFeign 10.* , 3.5版本之前的对应OpenFeign9.*

    1.5 相关的pom 依赖

         <dependency>
          <groupId>io.github.openfeign.form</groupId>
          <artifactId>feign-form</artifactId>
          <version>3.4.1</version>
        </dependency>
        <dependency>
          <groupId>io.github.openfeign.form</groupId>
          <artifactId>feign-form-spring</artifactId>
          <version>3.4.1</version>
        </dependency>
    

    1.6 附加一个调用方使用OpenFeign 上传文件和下载并返回给调用方客户端的demo

       
       @PostMapping(value = "upload")
       public BaseResult<String> test(MultipartFile file) {
           return fileFeign.upload(file);
       }
    
       @GetMapping(value = "download")
       public void download(@RequestParam(value = "filename") String filename,
           HttpServletResponse httpServletResponse) {
           httpServletResponse
               .setContentType("application/x-download;charset=" + Charsets.UTF_8.displayName());
           httpServletResponse.addHeader("Content-Disposition",
               "attachment;filename=" + this.reWriteChinese(filename));
           Response response = fileFeign.download(filename);
           Response.Body body = response.body();
           try (OutputStream outputStream = httpServletResponse.getOutputStream();
               InputStream inputStream = body.asInputStream()) {
               IOUtils.copy(inputStream, outputStream);
               outputStream.flush();
           } catch (IOException e) {
               log.error("下载文件异常 filepath:[{}]", filename, e);
           }
       }
    

    相关文章

      网友评论

          本文标题:OpenFeign 文件上传下载

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