前端请求 vue

Axios({
          method: 'get',
          url: 'http://IP地址:端口/previewFileStream',
          params: {
            filePath: '/home/NSY1312-02-06-00-00-06A.PDF',
          },
          headers:{
            'Content-Type': 'application/json;charset=UTF-8',
          },
          responseType: 'arraybuffer',
        }).then(function (res) {
          console.log(res);
        });

后端 java

     @GetMapping("/previewFileStream")
    public ResponseEntity<byte[]> previewFileStream(@RequestParam String filePath) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            FileInputStream fileInputStream = new FileInputStream(file);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }

            byte[] fileContent = byteArrayOutputStream.toByteArray();

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            headers.add("content-type", "application/pdf;chartset=UTF-8");
//            headers.add("Content-Disposition", "fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
            headers.setContentLength(fileContent.length);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileContent);
        } catch (FileNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

楷楷
4k 声望10.5k 粉丝

兴趣是最好的老师!