如果被调用服务方法有HttpServletResponse,会导致调用失败,因为Feign不能处理HttpServletResponse
使用返回值ResponseEntity<org.springframework.core.io.Resource>进行处理
java    @GetMapping("/download")
    public void  download(@RequestParam(value = "fileUrl") String fileUrl, HttpServletResponse response){
        try {
            ResponseEntity<org.springframework.core.io.Resource> responseEntity = remoteFileService.downloadByRes(fileUrl);;
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                org.springframework.core.io.Resource resource = responseEntity.getBody();
                if (resource != null) {
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-Disposition", "attachment;filename=" + resource.getFilename());
                    try (OutputStream outputStream = response.getOutputStream()) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = resource.getInputStream().read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        outputStream.flush();
                    }
                }
            } else {
                response.setStatus(responseEntity.getStatusCodeValue());
            }
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
java    @GetMapping(value = "/downloadByRes")
    public ResponseEntity<Resource> downloadByRes(@RequestParam(value = "fileUrl") String fileUrl);
java    @GetMapping("downloadByRes")
    public ResponseEntity<Resource> downloadByRes(String fileUrl) {
       return sysFileService.downloadFile(fileUrl);
    }
java    @Override
    public ResponseEntity<org.springframework.core.io.Resource> downloadFile(String fileUrl) {
        try {
            // 获取文件路径
            String filePath = getFileDir(fileUrl);
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException("文件不存在");
            }
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUrl.substring(fileUrl.lastIndexOf("/") + 1), StandardCharsets.UTF_8.toString()));
            headers.add("Content-Type", "application/octet-stream");
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new FileSystemResource(file));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
本文作者:Weee
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!