Spring Mvc下實現以文件流方式下載文件的方法示例

這篇文章主要介紹了Spring Mvc下實現以文件流方式下載文件的方法示例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

項目中需要對一個點擊事件進行下載操作,同時通過點擊事件,已經可以從jsp頁面獲取到需要訪問的URL和下載的文件名(數據庫獲取,jsp頁面顯示)。點擊事件JS如下:

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

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

 @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();// 通過輸入流獲取數據
 } catch (IOException ex) {
  result.setCode(0);
  ex.printStackTrace();
 }finally {
  if(conn != null) {
  conn.disconnect();
  }
 }
 return result;
 }
    

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

 @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();// 通過輸入流獲取數據
 
  byte[] buffer = readInputStream(fis);
  if (null != buffer && buffer.length > 0) {
  // 清空response
  response.reset();
  // 設置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();
  }
 }
 }
 
  /** 
   * 從輸入流中獲取數據 
   * @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();
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章