SpringBoot/SpringMVC文件下載方式


本篇文章引用外網博客代碼,共描述SpringMVC下三種文件下載方式,本人測試在SpringBoot(2.0以上版本)正常使用.
引用博客,強烈推薦https://www.boraji.com.

package com.boraji.tutorial.spring.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @author imssbora
 */
@Controller
public class FileDownloadController {

   private static final String FILE_PATH = "D:/e-Books/jsp_tutorial.pdf";

   @GetMapping("/")
   public String fileUploadForm(Model model) {
      return "fileDownloadView";
   }

   // Using ResponseEntity<InputStreamResource>
   @GetMapping("/download1")
   public ResponseEntity<InputStreamResource> downloadFile1() throws IOException {

      File file = new File(FILE_PATH);
      InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

      return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION,
                  "attachment;filename=" + file.getName())
            .contentType(MediaType.APPLICATION_PDF).contentLength(file.length())
            .body(resource);
   }

   // Using ResponseEntity<ByteArrayResource>
   @GetMapping("/download2")
   public ResponseEntity<ByteArrayResource> downloadFile2() throws IOException {

      Path path = Paths.get(FILE_PATH);
      byte[] data = Files.readAllBytes(path);
      ByteArrayResource resource = new ByteArrayResource(data);

      return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION,
                  "attachment;filename=" + path.getFileName().toString())
            .contentType(MediaType.APPLICATION_PDF).contentLength(data.length)
            .body(resource);
   }

   // Using HttpServletResponse
   @GetMapping("/download3")
   public void downloadFile3(HttpServletResponse resonse) throws IOException {
      File file = new File(FILE_PATH);
       
      // 示例中使用的是pdf,實際的content-type需要根據上傳文件時的content-type進行確定(最長可達255字節)
      resonse.setContentType("application/pdf");
      resonse.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
      BufferedInputStream inStrem = new BufferedInputStream(new FileInputStream(file));
      BufferedOutputStream outStream = new BufferedOutputStream(resonse.getOutputStream());
      
      byte[] buffer = new byte[1024];
      int bytesRead = 0;
      while ((bytesRead = inStrem.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
      }
      outStream.flush();
      inStrem.close();
   }
}

ResponseEntity表示HTTP響應,包含body,header以及status code.
ResponseEntity可以在RestTemplate 以及@Controller中使用.

PS:
如果您覺得我的文章對您有幫助,可以掃碼領取下紅包或掃碼支持(隨意多少,一分錢都是愛),謝謝!

支付寶紅包 支付寶 微信


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM