Spring Boot微服務間文件返回實現

 

Feign接口獲取文件流問題_Java_wyazyf的博客-CSDN博客
https://blog.csdn.net/wyazyf/article/details/93200033

 

 

Spring Boot微服務間文件返回實現

 


下層服務返回文件流 (即文件下載)

@GetMapping(value = "/v1/files/**/{file_name:.+}")
    public void downFile(@PathVariable("file_name") String fileName, HttpServletResponse response, HttpServletRequest request) {
//        String uploadPath = IFlieServiceRpc.findByStrategyKey(uploadDir);
        String url = request.getServletPath();//獲取url
        url = url.substring(url.lastIndexOf("files")).replace("files/", "");
        String uploadPath = null;
        String os = OSNameUtil.getOSname();
        if ("Windows".equals(os)) {
            uploadPath = winuploadDir;
        } else if ("Linux".equals(os)) {
            uploadPath = linuxuploadDir;
        }
        //截取時間戳
        String filename = "";//不帶時間戳的文件名
        String ownFilePathString = "";//自定義文件路徑
        if (url.lastIndexOf("/") > 0) {
            filename = url.substring(url.lastIndexOf("/") + 1);
            ownFilePathString = url.substring(0, url.lastIndexOf("/") + 1);
        } else {
            filename = url;
        }
        if (filename.indexOf("_") > 0) {
            filename = filename.substring(filename.indexOf("_") + 1);
        }
 
        String path = uploadPath + File.separator + url;
 
        String path1 = uploadPath + File.separator + ownFilePathString + filename;
 
        //判斷文件是否存在
        File file2 = new File(path);
        if (!file2.exists()) {
            LOGGER.equals("文件不存在");
            throw new SBRException("文件不存在");
        }
        String getSm4Key = null;
        try {
            getSm4Key = PropertyUtil.getProperty("sm4");
            if (getSm4Key != null && !"".equals(getSm4Key)) {
                SM4Utils.decryptFile(path, path1, getSm4Key);
            } else {
                renameFile(path, path1);
                //path1=path;
            }
        } catch (IOException e1) {
            if (getSm4Key != null && !"".equals(getSm4Key)) {//解析後的文件需要刪除
                File file = new File(path1);
                file.delete();
            }
            LOGGER.error("獲取sm4報錯,錯誤原因:" + e1);
            throw new SBRException("獲取sm4報錯,錯誤原因:" + e1);
        }
        File file = new File(path1);
        FileInputStream fis =null;
        try {
            if (file.exists()) {
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + new String((file.getName()).getBytes("GB2312"), "ISO8859-1"));
                response.setContentLength((int) file.length());
                response.setContentType("application/octet-stream");// 定義輸出類型
                fis = new FileInputStream(file);
                BufferedInputStream buff = new BufferedInputStream(fis);
                byte[] b = new byte[1024];// 相當於我們的緩存
                long k = 0;// 該值用於計算當前實際下載了多少字節
                OutputStream myout = response.getOutputStream();// 從response對象中得到輸出流,準備下載
                // 開始循環下載
                while (k < file.length()) {
                    int j = buff.read(b, 0, 1024);
                    k += j;
                    myout.write(b, 0, j);
                }
                myout.flush();
                myout.close();
                buff.close();
                if (getSm4Key != null && !"".equals(getSm4Key)) {
                    file.delete();
                }
            }
        } catch (Exception e) {
            if (getSm4Key != null && !"".equals(getSm4Key)) {//解析後的文件需要刪除
                file.delete();
            }
            LOGGER.error("文件下載流錯誤,錯誤原因:" + e);
            throw new SBRException("文件下載流錯誤,錯誤原因:" + e);
        } finally {
            if(fis!=null){
                try {
                    fis.close();
                    fis=null;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            try {
                if (getSm4Key == null && "".equals(getSm4Key)) {//沒加密的文件需要處理
                    renameFile(path1, path);
                }
            } catch (IOException e) {
                LOGGER.error("重命名失敗,失敗原因:" + e);
                throw new SBRException("重命名失敗,失敗原因:" + e);
            }
        }
    }

 

 

上下層服務間Feign接口調用

import feign.Response;

@FeignClient("prometheus-file")
public interface FileFeignClient {
 
    @GetMapping(value = "/file/api//v1/files/{file_name}",consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    Response downFile(@PathVariable("file_name") String fileName);
}

 

 

上層服務把下層服務的文件流返回給前端 (實現瀏覽器中文件下載)

    @GetMapping("/file/download")
    public void downloadProject(HttpServletResponse httpServletResponse)
        throws IOException {

        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        InputStream inputStream = feignBody.asInputStream();

        Response feignResponse = genAtomicFeign.downFile("file_name");
        Response.Body feignBody = feignResponse.body();

        feignResponse.headers().forEach((String key, Collection<String> value) -> {
            httpServletResponse.setHeader(key, ((LinkedList<String>) value).get(0));
        });

        byte[] c = new byte[1024];
        int length;
        while ((length = inputStream.read(c)) > 0) {
            servletOutputStream.write(c, 0, length);
        }

        servletOutputStream.flush();
        servletOutputStream.close();
    }

 

 

上層服務把下層服務的文件流保存爲本地文件


/**
     * 將文件寫入隨機文件,並返回路徑
     * @param fileName 文件名稱
     * @return
     */
    public String  getFilePath(String fileName){
        InputStream inputStream = null;
        //獲得文件流
        Response response =fileFeignClient.downFile(fileName);
        Response.Body body = response.body();
 
        String filePath ="";
        FileOutputStream fos = null;
        try {
            //獲取response中的文件流
            inputStream = body.asInputStream();
//            byte[] b = new byte[inputStream.available()];
//            inputStream.read(b);
            //臨時目錄
            String folder=System.getProperty("java.io.tmpdir");
            int random = (int)(1+Math.random()*(10-1+1));
            String sj = String.valueOf(DateUtil.getCurrentDate().getTime());
            //臨時路徑+文件名稱
            filePath = folder + sj+random+fileName.substring(fileName.lastIndexOf("."));
            //寫入文件
            fos= new FileOutputStream(filePath);
            byte[] c = new byte[1024];
            int length;
            while((length= inputStream.read(c))>0){
                fos.write(c,0,length);
            }
 
        } catch (IOException e1) {
            e1.printStackTrace();
        }finally{
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章