溫馨提示×

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

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

怎么在Spring Mvc中以文件流方式下載文件

發(fā)布時(shí)間:2021-05-27 17:58:00 來(lái)源:億速云 閱讀:209 作者:Leah 欄目:編程語(yǔ)言

本篇文章給大家分享的是有關(guān)怎么在Spring Mvc中以文件流方式下載文件,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。

function downloadFile(filePath,fileName){
 
 fileName = fileName.substr(0,fileName.lastIndexOf("."));
 $.ajax({
   async : false, 
   cache:false, 
   type: 'get',
   dataType : "json", 
   url: RootPath() + "/checkDownload",//請(qǐng)求的action路徑 
   data:{url:filePath},
   error: function () {//請(qǐng)求失敗處理函數(shù) 
     alert("下載失敗");
   }, 
   success:function(json) { //請(qǐng)求成功后處理函數(shù)。
   var code = json.code;
   if(code) {
    window.location.href = RootPath()+"/todownload?url="+filePath+"&name="+fileName;
   }else {
    layer.alert(fileName+' 文件不存在'); 
   }
   } 
 });
 
}

該ajax調(diào)用后臺(tái)(checkDownload)方法,首先判斷從該url能否獲得指定下載的文件,如果獲取不到,方法返回參數(shù)code=0,頁(yè)面彈出“...文件不存在”。

 @RequestMapping("/checkDownload")
 @ResponseBody
 public Result checkDownload(String url,HttpServletResponse response) {
 Result result = Result.createSuccessResult();
 HttpURLConnection conn = null;
 try {
  URL path = new URL(url);
  conn = (HttpURLConnection) path.openConnection();
  conn.setRequestMethod("GET");
  conn.setConnectTimeout(5 * 1000);
  conn.getInputStream();// 通過(guò)輸入流獲取數(shù)據(jù)
 } catch (IOException ex) {
  result.setCode(0);
  ex.printStackTrace();
 }finally {
  if(conn != null) {
  conn.disconnect();
  }
 }
 return result;
 }

如果checkDownload方法中能夠正確獲得資源,方法返回參數(shù)code=1,ajax成功執(zhí)行:window.location.href = RootPath()+"/todownload?url="+filePath+"&name="+fileName;   調(diào)用(todownload)方法,傳入url和name,執(zhí)行文件下載。

 @RequestMapping("/todownload")
 @ResponseBody
 public void download(String url, String name, HttpServletResponse response) {
 HttpURLConnection conn = null;
 try {
  File file = new File(url);
  // 取得文件的后綴名。
  String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
  StringBuffer buffername = new StringBuffer(name);
  String filename = buffername.append(".").append(ext).toString();
 
  URL path = new URL(url);
  conn = (HttpURLConnection) path.openConnection();
  conn.setRequestMethod("GET");
  conn.setConnectTimeout(5 * 1000);
  InputStream fis = conn.getInputStream();// 通過(guò)輸入流獲取數(shù)據(jù)
 
  byte[] buffer = readInputStream(fis);
  if (null != buffer && buffer.length > 0) {
  // 清空response
  response.reset();
  // 設(shè)置response的Header
  response.addHeader("Content-Disposition","attachment;filename="+ new String((filename).getBytes("GBK"),"ISO8859_1"));
  response.addHeader("Content-Length", "" + buffer.length);
  OutputStream toClient = response.getOutputStream();
  response.setContentType("application/octet-stream");
  toClient.write(buffer);
  toClient.flush();
  toClient.close();
  }
 
 } catch (IOException ex) {
  ex.printStackTrace();
 }finally {
  if(conn != null) {
  conn.disconnect();
  }
 }
 }
 
  /** 
   * 從輸入流中獲取數(shù)據(jù) 
   * @param inStream 輸入流 
   * @return 
   * @throws Exception 
   */ 
 private byte[] readInputStream(InputStream fis) throws IOException {
  ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
     byte[] buffer = new byte[1024]; 
     int len = 0; 
     while( (len=fis.read(buffer)) != -1 ){ 
       outStream.write(buffer, 0, len); 
     } 
     fis.close(); 
     return outStream.toByteArray();
 }

PS:Spring MVC 文件流形式下載(返回)視頻文件

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 文件流形式下載視頻
 * @author Front Ng
 * @date 2019-05-23 09:25
 **/

@Controller
@RequestMapping(value = "/download")
@Api(value = "下載", tags = "下載")
public class DownloadController {


  @ApiOperation(value = "下載視頻")
  @RequestMapping(method = RequestMethod.GET)
  public void download(HttpServletResponse response) throws IOException {

    File file = new File("/Users/front/Downloads/123.mp4");

    FileInputStream inputStream = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];
    int length = inputStream.read(data);
    inputStream.close();

    String fileName = URLEncoder.encode("文件流形式視頻.mp4", "UTF-8");

    response.setContentType("application/octet-stream;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    response.addHeader("Content-Length", "" + data.length);

    OutputStream stream = response.getOutputStream();
    stream.write(data);
    stream.flush();
    stream.close();
  }
}

以上就是怎么在Spring Mvc中以文件流方式下載文件,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向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