溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot如何實(shí)現(xiàn)文件下載功能

發(fā)布時(shí)間:2023-03-23 15:49:44 來(lái)源:億速云 閱讀:171 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹“SpringBoot如何實(shí)現(xiàn)文件下載功能”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“SpringBoot如何實(shí)現(xiàn)文件下載功能”文章能幫助大家解決問(wèn)題。

1. 將文件以流的形式一次性讀取到內(nèi)存,通過(guò)響應(yīng)輸出流輸出到前端

/**
 * @param path     想要下載的文件的路徑
 * @param response
 * @功能描述 下載文件:
 */
@RequestMapping("/download")
public void download(String path, HttpServletResponse response) {
    try {
        // path是指想要下載的文件的路徑
        File file = new File(path);
        log.info(file.getPath());
        // 獲取文件名
        String filename = file.getName();
        // 獲取文件后綴名
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        log.info("文件后綴名:" + ext);

        // 將文件寫(xiě)入輸入流
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStream fis = new BufferedInputStream(fileInputStream);
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();

        // 清空response
        response.reset();
        // 設(shè)置response的Header
        response.setCharacterEncoding("UTF-8");
        //Content-Disposition的作用:告知瀏覽器以何種方式顯示響應(yīng)返回的文件,用瀏覽器打開(kāi)還是以附件的形式下載到本地保存
        //attachment表示以附件方式下載   inline表示在線打開(kāi)   "Content-Disposition: inline; filename=文件名.mp3"
        // filename表示文件的默認(rèn)名稱,因?yàn)榫W(wǎng)絡(luò)傳輸只支持URL編碼的相關(guān)支付,因此需要將文件名URL編碼后進(jìn)行傳輸,前端收到后需要反編碼才能獲取到真正的名稱
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        // 告知瀏覽器文件的大小
        response.addHeader("Content-Length", "" + file.length());
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outputStream.write(buffer);
        outputStream.flush();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

2. 將輸入流中的數(shù)據(jù)循環(huán)寫(xiě)入到響應(yīng)輸出流中,而不是一次性讀取到內(nèi)存,通過(guò)響應(yīng)輸出流輸出到前端

/**
* @param path     指想要下載的文件的路徑
* @param response
* @功能描述 下載文件:將輸入流中的數(shù)據(jù)循環(huán)寫(xiě)入到響應(yīng)輸出流中,而不是一次性讀取到內(nèi)存
*/
@RequestMapping("/downloadLocal")
public void downloadLocal(String path, HttpServletResponse response) throws IOException {
   // 讀到流中
   InputStream inputStream = new FileInputStream(path);// 文件的存放路徑
   response.reset();
   response.setContentType("application/octet-stream");
   String filename = new File(path).getName();
   response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
   ServletOutputStream outputStream = response.getOutputStream();
   byte[] b = new byte[1024];
   int len;
   //從輸入流中讀取一定數(shù)量的字節(jié),并將其存儲(chǔ)在緩沖區(qū)字節(jié)數(shù)組中,讀到末尾返回-1
   while ((len = inputStream.read(b)) > 0) {
       outputStream.write(b, 0, len);
   }
   inputStream.close();
}

3. 下載網(wǎng)絡(luò)文件到本地

/**
* @param path       下載后的文件路徑和名稱
* @param netAddress 文件所在網(wǎng)絡(luò)地址
* @功能描述 網(wǎng)絡(luò)文件下載到服務(wù)器本地
*/
@RequestMapping("/netDownloadLocal")
public void downloadNet(String netAddress, String path) throws IOException {
	  URL url = new URL(netAddress);
	  URLConnection conn = url.openConnection();
	  InputStream inputStream = conn.getInputStream();
	  FileOutputStream fileOutputStream = new FileOutputStream(path);
	
	  int bytesum = 0;
	  int byteread;
	  byte[] buffer = new byte[1024];
	  while ((byteread = inputStream.read(buffer)) != -1) {
	      bytesum += byteread;
	      System.out.println(bytesum);
	      fileOutputStream.write(buffer, 0, byteread);
	  }
	  fileOutputStream.close();
}

4. 網(wǎng)絡(luò)文件獲取到服務(wù)器后,經(jīng)服務(wù)器處理后響應(yīng)給前端

/**
 * @param netAddress
 * @param filename
 * @param isOnLine
 * @param response
 * @功能描述 網(wǎng)絡(luò)文件獲取到服務(wù)器后,經(jīng)服務(wù)器處理后響應(yīng)給前端
 */
@RequestMapping("/netDownLoadNet")
public void netDownLoadNet(String netAddress, String filename, boolean isOnLine, HttpServletResponse response) throws Exception {

    URL url = new URL(netAddress);
    URLConnection conn = url.openConnection();
    InputStream inputStream = conn.getInputStream();

    response.reset();
    response.setContentType(conn.getContentType());
    if (isOnLine) {
        // 在線打開(kāi)方式 文件名應(yīng)該編碼成UTF-8
        response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(filename, "UTF-8"));
    } else {
        //純下載方式 文件名應(yīng)該編碼成UTF-8
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
    }

    byte[] buffer = new byte[1024];
    int len;
    OutputStream outputStream = response.getOutputStream();
    while ((len = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, len);
    }
    inputStream.close();
}

5. 常見(jiàn)異常和問(wèn)題

(1)響應(yīng)對(duì)象無(wú)需通過(guò)return返回

SpringBoot如何實(shí)現(xiàn)文件下載功能

原因:  響應(yīng)對(duì)象是可以不用作為方法返回值返回的,其在方法執(zhí)行時(shí)已經(jīng)開(kāi)始輸出,且其無(wú)法與@RestController配合,以JSON格式返回給前端

SpringBoot如何實(shí)現(xiàn)文件下載功能

SpringBoot如何實(shí)現(xiàn)文件下載功能

解決辦法: 刪除return語(yǔ)句

(2)返回前端的文件名必須進(jìn)行URL編碼

原因: 網(wǎng)絡(luò)傳輸只能傳輸特定的幾十個(gè)字符,需要將漢字、特殊字符等經(jīng)過(guò)Base64等編碼來(lái)轉(zhuǎn)化為特定字符,從而進(jìn)行傳輸,而不會(huì)亂碼

URLEncoder.encode(fileName, "UTF-8")

(3)IO流有待學(xué)習(xí)

1:read() : 從輸入流中讀取數(shù)據(jù)的下一個(gè)字節(jié),返回0到255范圍內(nèi)的int字節(jié)值。如果因?yàn)橐呀?jīng)到達(dá)流末尾而沒(méi)有可用的字節(jié),則返回-1。在輸入數(shù)據(jù)可用、檢測(cè)到流末尾或者拋出異常前,此方法一直阻塞。

2:read(byte[] b) : 從輸入流中讀取一定數(shù)量的字節(jié),并將其存儲(chǔ)在緩沖區(qū)數(shù)組 b 中。以整數(shù)形式返回實(shí)際讀取的字節(jié)數(shù)。在輸入數(shù)據(jù)可用、檢測(cè)到文件末尾或者拋出異常前,此方法一直阻塞。如果 b 的長(zhǎng)度為 0,則不讀取任何字節(jié)并返回 0;否則,嘗試讀取至少一個(gè)字節(jié)。如果因?yàn)榱魑挥谖募┪捕鴽](méi)有可用的字節(jié),則返回值 -1

關(guān)于“SpringBoot如何實(shí)現(xiàn)文件下載功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI