spring cloud feign 檔案上傳和檔案下載

致未來的自己發表於2019-02-24

檔案上傳參考文件:http://blog.didispace.com/spring-cloud-starter-dalston-2-4/

檔案下載參考文件:https://blog.csdn.net/aaronsimon/article/details/82710979

我的spring boot ,spring cloud 版本是:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/>
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.M9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

 

服務呼叫方 feign檔案下載需要配置的config:

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

@Configuration
public class FeignMultipartSupportConfig {
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder();
    }
}  

 

對應的feign pom.xml需要引入

     <!--feign upload file-->
        <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form-spring</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>  

 

服務呼叫方controller:

import com.yft.common.annotation.Log;
import com.yft.sys.modules.test.fileclient.FileTestClient;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * feign 熔斷器示例
 *
 * @author oKong
 */
@RestController
@Slf4j
public class FileController {

    @Autowired
    FileTestClient fileTestClient;

    @Log("檔案上傳測試")
    @PostMapping("/upload")
    public Object upload(MultipartFile file) {
        log.info("使用feign呼叫服務,檔案上傳");
        return fileTestClient.upload(file);
    }

    @Log("檔案下載測試")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<byte[]> downFile() {
        log.info("使用feign呼叫服務 檔案下載");

        ResponseEntity<byte[]> result = null;
        InputStream inputStream = null;
        try {
            // feign檔案下載
            Response response = fileTestClient.download();
            Response.Body body = response.body();
            inputStream = body.asInputStream();
            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);
            HttpHeaders heads = new HttpHeaders();
            heads.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=lr.xls");
            heads.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

            result = new ResponseEntity<byte[]>(b, heads, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

服務呼叫方feign client寫法(檔案上傳主要是上面第一步配置,檔案下載主要是返回的feign 的response):

import com.yft.sys.modules.ClientUrl;
import com.yft.sys.modules.test.fileclient.impl.FileTestClientFallbackFactory;
import feign.Response;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lr
 */
@FeignClient(name = ClientUrl.SYSTEM_NAME, fallbackFactory = FileTestClientFallbackFactory.class)
@Component
public interface FileTestClient {

    /**
     * 上傳檔案測試
     *
     * @return
     */
    @PostMapping(value = ClientUrl.PRE_REQUEST_RUL + "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Object upload(MultipartFile file);

    /**
     * 下載檔案測試
     */
    @RequestMapping(value = ClientUrl.PRE_REQUEST_RUL + "/file/download", method = RequestMethod.GET)
    Response download();

}

服務呼叫方 feign client 異常類:

import com.yft.sys.modules.test.fileclient.FileTestClient;
import feign.Response;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lr
 */
@Slf4j
@Component
public class FileTestClientFallbackFactory implements FallbackFactory<FileTestClient> {
    @Override
    public FileTestClient create(Throwable cause) {

        return new FileTestClient() {
            @Override
            public Object upload(MultipartFile file) {
                log.error("fallback; file upload reason was: " + cause.getMessage());
                return null;
            }

            @Override
            public Response download() {
                log.error("fallback; file download reason was: " + cause.getMessage());
                return null;
            }
        };
    }
}

 

服務提供方呢與原來寫法一樣,沒差別

   @PostMapping(value = "upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R upload(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            fileName = FileUtils.renameToUUID(fileName);
            String resPath = FileUtils.saveFile(file.getBytes(), filePath, fileName);
//            fileService.save(new FileDO() {{
//                setCreateDate(new Date());
//                setUrl("http://localhost:8004" + filePre + "/"+resPath);
//                setType(1);
//            }});
            return R.ok().put("resPath", resPath);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("檔案上傳失敗");
        }
    }

    @GetMapping("/download")
    public void downLoad(HttpServletResponse response) throws IOException {
    //這裡示意下載excel檔案,自己隨便下載點東西
     /*我們先定義一個巢狀的List,List的元素也是一個List,內層的一個List代表一行資料, 每行都有4個單元格,最終list物件代表多行資料。*/ List<String> row1 = CollUtil.newArrayList("aa", "bb", "cc", "dd"); List<String> row2 = CollUtil.newArrayList("aa1", "bb1", "cc1", "dd1"); List<String> row3 = CollUtil.newArrayList("aa2", "bb2", "cc2", "dd2"); List<String> row4 = CollUtil.newArrayList("aa3", "bb3", "cc3", "dd3"); List<String> row5 = CollUtil.newArrayList("aa4", "bb4", "cc4", "dd4"); List<List<String>> rows = CollUtil.newArrayList(row1, row2, row3, row4, row5); // 然後我們建立ExcelWriter物件後寫出資料: // 通過工具類建立writer,預設建立xls格式 ExcelWriter writer = ExcelUtil.getWriter(); // 一次性寫出內容,使用預設樣式 writer.write(rows); //out為OutputStream,需要寫出到的目標流 //response為HttpServletResponse物件 response.setContentType("application/vnd.ms-excel;charset=utf-8"); //test.xls是彈出下載對話方塊的檔名,不能為中文,中文請自行編碼 response.setHeader("Content-Disposition", "attachment;filename=test.xls"); ServletOutputStream out = response.getOutputStream(); writer.flush(out); // 關閉writer,釋放記憶體 writer.close(); }

 

檔案上傳配置yml

#上傳檔案配置
app:
filePath: D:/uploaded_files/
pre: /files
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${app.filePath}")
String filePath;

@Value("${app.pre}")
String pre;

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(pre + "/**").addResourceLocations("file:///" + filePath);
}

}

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.UUID;

public class FileUtils {
    public static String saveFile(byte[] file, String filePath, String fileName) {
        int random = (int) (Math.random() * 100 + 1);
        int random1 = (int) (Math.random() * 100 + 1);
        filePath = filePath + random + File.separator + random1 + File.separator;
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filePath + fileName);
            FileChannel fileChannel = fileOutputStream.getChannel();
            ByteBuffer buf = ByteBuffer.wrap(file);
            while (fileChannel.write(buf) != 0) {
            }
        } catch (Exception e) {

        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //url
        return random + "/" + random1 + "/" + fileName;
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果檔案路徑所對應的檔案存在,並且是一個檔案,則直接刪除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static String renameToUUID(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}

   

相關文章