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;
    }

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值