Feign文件上传与下载

  • 1. 下载
  • 2. 调用
  • 3. 上传
  • 4. 调用

client

    /**
     * 下载
     *
     * @param path
     */
    @GetMapping(value = "/download", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    //直接把流写到Response // 注意:这个Response是feign的
    Response download(@RequestParam("path") String path);

HystrixFallbackFactory

            @Override
            public Response download(String path) {
                return null;
            }

controller

    /**
     * 下载
     *
     * @param path
     * @param response
     */
    @GetMapping(value = "/download", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void download(@RequestParam("path") String path, HttpServletResponse response) {
        //获取相对路径    // 去掉路径的第1个字符 //拿到的就是group1/xxx //
        String pathTemp = path.substring(1);
        //获取第一个"/"之前的字符 //获取组名
        String groupName = pathTemp.substring(0, pathTemp.indexOf("/"));
        //indexOf("/)返回"/"在字符串中第一次出现处的索引
        //substring(数字n)去掉pathTemp这个字符串前面的n个字符
        String remotePath = pathTemp.substring(pathTemp.indexOf("/") + 1);
        System.out.println(groupName);
        System.out.println(remotePath);
        //注意关流
        OutputStream os = null;
        InputStream is = null;
        try {
            byte[] datas = FastDfsApiOpr.download(groupName, remotePath);
            os = response.getOutputStream(); //直接给以流方式进行返回
            is = new ByteInputStream(datas, datas.length);
            IOUtils.copy(is, os);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("download_error..." + e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

2. 调用

        // 下载fastdfs上面的模板压缩包
        Response response = fastDFSClient.download(templateUrl);
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //获得输入流资源
            inputStream = response.body().asInputStream();
            // 所有静态化中数据都写入操作系统的临时目录(这个可以跨操作系统,而且临时目录的东西会自动维护,无需手动删除)
            String tempdir = System.getProperty("java.io.tmpdir");
            System.out.println(tempdir + "-------------------------------临时目录");
            // 要下载压缩包的路径
            String zipPath = tempdir + "/temp.zip";
            // 要解压到的路径
            String unZipPath = tempdir + "/temp/";
            // 获得输出流资源
            fileOutputStream = new FileOutputStream(zipPath);
            // 保存到本地 //import org.apache.commons.io.IOUtils;
            IOUtils.copy(inputStream, fileOutputStream); //保存到本地

3. 上传

interface导包


    io.github.openfeign.form
    feign-form
    2.1.0


    io.github.openfeign.form
    feign-form-spring
    2.1.0

interface的config

package cn.wangningbo.hrmconfig;

import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;

@Configuration
public class FeignMultipartSupportConfig {

    @Bean
    @Primary
    @Scope("prototype")
    public Encoder multipartFormEncoder() {
        return new SpringFormEncoder();
    }

    @Bean
    public feign.Logger.Level multipartLoggerLevel() {
        return feign.Logger.Level.FULL;
    }
}

这个时候client的configuration就要指定到自己的配置了

configuration = FeignMultipartSupportConfig.class
@RequestPart("file")
package cn.wangningbo.hrm.client;

import cn.wangningbo.hrm.util.AjaxResult;
import cn.wangningbo.hrmconfig.FeignMultipartSupportConfig;
import feign.Response;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author wangningbo
 * @since 2019-09-04
 */
//@FeignClient(value = "ZUUL-FASTDFS", configuration = FeignClientsConfiguration.class,
@FeignClient(value = "HRM-FASTDFS", configuration = FeignMultipartSupportConfig.class,
        fallbackFactory = FastDFSClientHystrixFallbackFactory.class)
@RequestMapping("/fastdfs")
public interface FastDFSClient {
    /**
     * 上传
     *
     * @param file
     * @return
     */
//    @RequestMapping(value = "/upload", method = RequestMethod.POST)
//    String upload(@RequestBody MultipartFile file);
    @PostMapping(value="/upload", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
            , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    String upload(@RequestPart("file") MultipartFile file);
    /**
     * 删除
     *
     * @param path
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    AjaxResult delete(@RequestParam("path") String path);

    /**
     * 下载
     *
     * @param path
     */
    @GetMapping(value = "/download", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    //直接把流写到Response // 注意:这个Response是feign的
    Response download(@RequestParam("path") String path);

}

controller

    /**
     * 上传
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/upload", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
            , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String upload(@RequestPart("file") MultipartFile file) {

4. 调用

调用方导包



    commons-fileupload
    commons-fileupload
    1.3.1

调用

@Autowired
private FastDfsClient fastDfsClient;

@Test
public void test1() throws Exception{
    FileItem fileItem = createFileItem(new File("C:\\Users\\Administrator\\Desktop\\问题.txt"));
    MultipartFile mfile = new CommonsMultipartFile(fileItem);
    fastDfsClient.upload(mfile);
}
/*
创建FileItem
 */
    private FileItem createFileItem(File file, String filedName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(filedName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

你可能感兴趣的:(Feign文件上传与下载)