FeignClient调用内部服务下载文件正确打开方式

发布时间:2023年12月22日

文件服务器提供的接口

controller层

/**
?* 绝对路径-文件下载
?*/
@GetMapping("/absolutePathDownload")
public void absolutePathDownload(String fileName, HttpServletResponse response) {
? ? sysFileService.absolutePathDownload(fileName, response);
}


service接口层?

 /**
? ? ?* 绝对路径-文件下载
? ? ?*
? ? ?* @param fileName 文件路径名称
? ? ?* @param response 返回值
? ? ?*/
? ? void absolutePathDownload(String fileName, HttpServletResponse response);


impl实现层

?

@Override
? ? public void absolutePathDownload(String fileName, HttpServletResponse response) {
? ? ? ? InputStream inputStream = null;
? ? ? ? OutputStream outputStream = null;
? ? ? ? try {
? ? ? ? ? ? outputStream = response.getOutputStream();
? ? ? ? ? ? // 获取文件对象
? ? ? ? ? ? inputStream = XXX
? ? ? ? ? ? byte buf[] = new byte[1024];
? ? ? ? ? ? int length = 0;
? ? ? ? ? ? response.reset();
? ? ? ? ? ? response.setHeader("Content-Disposition", "attachment;filename=" +
? ? ? ? ? ? ? ? ? ? URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
? ? ? ? ? ? response.setContentType("application/octet-stream");
? ? ? ? ? ? response.setCharacterEncoding("UTF-8");
? ? ? ? ? ? // 输出文件
? ? ? ? ? ? while ((length = inputStream.read(buf)) > 0) {
? ? ? ? ? ? ? ? outputStream.write(buf, 0, length);
? ? ? ? ? ? }
? ? ? ? ? ? logger.info("下载成功");
? ? ? ? ? ? inputStream.close();
? ? ? ? } catch (Throwable ex) {
? ? ? ? ? ? logger.error("下载文件失败:{}", ex);
? ? ? ? ? ? response.setHeader("Content-type", "text/html;charset=UTF-8");
? ? ? ? ? ? String data = "文件下载失败";
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? OutputStream ps = response.getOutputStream();
? ? ? ? ? ? ? ? ps.write(data.getBytes("UTF-8"));
? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? }
? ? ? ? } finally {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? outputStream.close();
? ? ? ? ? ? ? ? if (inputStream != null) {
? ? ? ? ? ? ? ? ? ? inputStream.close();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? }
? ? ? ? }
? ? }


FeignClient接口正确定义

    /**
     * 绝对路径-下载文件
     *
     * @param fileName 文件路径
     * @return 结果
     */
    @GetMapping(value = "/absolutePathDownload")
    Response absolutePathDownload(@RequestParam("fileName") String fileName);

正确调用一:因为这个返回的保存JSON格式的text文件,所以可以这么转换成实体

 /**
     * 内部服务器调用
     */
    private List<AtlasEntity.AtlasEntityWithExtInfo> initAtlasEntityList(String url) throws IOException {
        Response response = remoteFileService.absolutePathDownload(url);
        Response.Body body = response.body();
        InputStream inputStream = body.asInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        reader.close();
        ObjectMapper mapper = new ObjectMapper();
        // 将响应转换为 JSON
        String json = stringBuilder.toString();
        return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, AtlasEntity.AtlasEntityWithExtInfo.class));
    }

正确调用二:

    @PostMapping("/download")
    public void download(@RequestBody ChuanId chuanId, HttpServletResponse response) {
        if (chuanId != null && StringUtils.isNotEmpty(chuanId.getId())) {
            QualityRequire qualityRequire = qualityRequireService.selectQualityRequireByDemandNo(chuanId.getId());
            String annexPath = qualityRequire.getAnnexPath();
            Response response1 = fileService.absolutePathDownload(annexPath);
            initResponse(response, annexPath, response1);
        }
    }

//再次转换成文件

private void initResponse(HttpServletResponse response, String annexPath, Response response1) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            // 获取文件对象
            inputStream = response1.body().asInputStream();
            byte[] buf = new byte[1024];
            int length = 0;
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(annexPath.substring(annexPath.lastIndexOf("/") + 1), "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            // 输出文件
            while ((length = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            logger.info("下载成功");
            inputStream.close();
        } catch (Throwable ex) {
            logger.error("下载文件失败", ex);
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            String data = "文件下载失败";
            try {
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            try {
                assert outputStream != null;
                outputStream.close();
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


?

文章来源:https://blog.csdn.net/m18030221734_1/article/details/135148040
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。