SpringBoot示例,第2期:文件下载_springboot下载word文件

SpringBoot示例,第2期:文件下载_springboot下载word文件

编程文章jaq1232025-10-08 18:35:5729A+A-

利用ResponseEntity

利用SpringBoot的ResponseEntity

@GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws MalformedURLException {
        // 文件存储路径,这里需要根据实际情况修改  
        String filePath = "E:\\xxxx\\upload\\";
        Path path = Paths.get(filePath).resolve(fileName).normalize();
        Resource resource = new UrlResource(path.toUri());
        if (resource.exists() || resource.isReadable()) {
            String contentType = null;
            try {
                contentType = Files.probeContentType(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

利用Response持续输出

输入流中的数据循环写入到响应输出流中,而不是一次性读取到内存,通过响应输出流输出到前端

@GetMapping("/download")
    public void downloadFile(HttpServletResponse response) {
        String fileName = "example.txt";
        String filePath = "E:\\xxx\\upload\\";
        File file = new File(filePath + fileName);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            // Handle exceptions
        }
    }

利用Response一次性响应

输入流中的数据一次性读取到内存,通过响应输出流输出到前端

@GetMapping("/download2/{fileName:.+}")
    public void downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        String filePath = "E:\\xxx\\upload\\";
        FileInputStream fileInputStream = new FileInputStream(filePath+fileName);
        InputStream fis = new BufferedInputStream(fileInputStream);
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        
        OutputStream outputStream = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Content-Type", "application/octet-stream");
            response.setContentType("application/octet-stream; charset=UTF-8");
            outputStream = response.getOutputStream();
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
            // ignored
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
点击这里复制本文地址 以上内容由jaq123整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

苍茫编程网 © All Rights Reserved.  蜀ICP备2024111239号-21