Spring Mvc下實現(xiàn)以文件流方式下載文件的方法示例
項目中需要對一個點擊事件進行下載操作,同時通過點擊事件,已經(jīng)可以從jsp頁面獲取到需要訪問的URL和下載的文件名(數(shù)據(jù)庫獲取,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 () {//請求失敗處理函數(shù) alert("下載失敗"); }, success:function(json) { //請求成功后處理函數(shù)。 var code = json.code; if(code) { window.location.href = RootPath()+"/todownload?url="+filePath+"&name="+fileName; }else { layer.alert(fileName+' 文件不存在'); } } }); }
該ajax調(diào)用后臺(checkDownload)方法,首先判斷從該url能否獲得指定下載的文件,如果獲取不到,方法返回參數(shù)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();// 通過輸入流獲取數(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();// 通過輸入流獲取數(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(); } }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java多線程執(zhí)行處理業(yè)務時間太久解決方法代碼示例
這篇文章主要介紹了Java多線程執(zhí)行處理業(yè)務時間太久解決方法代碼示例的相關(guān)資料,具有一定借鑒價值,需要的朋友可以參考下。2017-12-12scala 隱式轉(zhuǎn)換與隱式參數(shù)的使用方法
這篇文章主要介紹了scala 隱式轉(zhuǎn)換與隱式參數(shù)的使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11關(guān)于SpringSecurity認證邏輯源碼分析
這篇文章主要介紹了關(guān)于SpringSecurity認證邏輯源碼分析,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07SpringBoot自定義starter啟動器的實現(xiàn)思路
這篇文章主要介紹了SpringBoot如何自定義starter啟動器,通過starter的自定義過程,能夠加深大家對SpringBoot自動配置原理的理解,需要的朋友可以參考下2022-10-10