欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springcloud Feign 文件上传/输入流上传

程序员文章站 2022-04-15 19:05:35
1.1 feign客户端接口(写在你的业务的微服务里)import java.util.Map;import org.springframework.beans.factory.ObjectFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.http.HttpMessageConverters;import org.sp...

1.1 feign客户端接口(写在你的业务的微服务里)

import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;

/**
feign客户端
*/
@FeignClient(value = "smartControlPlatform-sftpServer",configuration = SftpService.MultipartSupportConfig.class)
public interface SftpService {
    
    //带参数的对应feign服务接口
    @RequestMapping(value = "sftpUpload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    //注意此处File必须使用@RequestPart注解,这个容易忽略,使用其他注解会报错
    //feign服务里的使用正常的@RequestParam,在下方会有体现
    public Map<String,Object> sftpUpload(@RequestPart("file")MultipartFile file , @RequestParam Map<String,Object> map);
 
 	//关键内部类,此处制定了注入的feignFormEncoder可以覆盖掉原本的encoder
 	//该方式可以让发送multipartFile成为可能
    class MultipartSupportConfig {
        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;
 
        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
    }
 
}

1.2 调用feignService

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.gyx.test.main.config.SftpService;

@Component
public class SftpUpload {

    @Resource
    SftpService sftpService;

    private static final Logger log = LoggerFactory.getLogger(SftpUpload.class.getName());

    /**
     * @Title: uploadToSftp
     * @Description: 上傳文件到Sftp工具類
     * @param file  前台上傳的文件
     * @param model 文件夾名
     * @return 返回上傳後訪問路徑
     * @author: B19072502
     */
    public String uploadToSftp(MultipartFile file, String model) {
        try {
            return uploadToSftp(file.getInputStream(),model, file.getOriginalFilename());
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * @Title: uploadToSftp
     * @Description: 傳入文件流和文件名上傳文件
     * @param inputStream
     * @param model
     * @param fileName
     * @return 文件地址
     * @author: B19072502
     */
    public String uploadToSftp(InputStream inputStream, String model, String fileName) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("model", model);
            MultipartFile file = getMulFile(inputStream, fileName);
            Result result = sftpService.sftpUpload(file, map);
            System.out.println(result);
            return result.get("data").toString();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

	//获取传输的multipartFile,将输入流+文件名转成multipartFile文件,去调用feignClient
    public MultipartFile getMulFile(InputStream inputStream, String fileName) {
        FileItem fileItem = createFileItem(inputStream, fileName);
        //CommonsMultipartFile是feign对multipartFile的封装,但是要FileItem类对象
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }
	
	//FileItem类对象创建
    public FileItem createFileItem(InputStream fis, String fileName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "file";
        FileItem item = factory.createItem(textFieldName, "multipart/form-data", true, fileName);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        //使用输出流输出输入流的字节
        try {
            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;
    }

}

2.sftp微服务端配置(使用了JSCH,在我的其他博文里有)

springcloud jsch sftp微服务

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class SftpUploadController {
    
    @Autowired
    SftpUpload sftpUpload;
    
    @RequestMapping("/sftpUpload")
    public Result sftpUpload(@RequestParam("file")MultipartFile file , @RequestParam Map<String,Object> map) {
        //省略业务逻辑
        //下方内容就是正常的controller获取到文件调用jsch上传
    } 
    
}

本文地址:https://blog.csdn.net/qq_33883147/article/details/107683552