Spring Mvc下實(shí)現(xiàn)以文件流方式下載文件的方法示例
項(xiàng)目中需要對(duì)一個(gè)點(diǎn)擊事件進(jìn)行下載操作,同時(shí)通過(guò)點(diǎn)擊事件,已經(jīng)可以從jsp頁(yè)面獲取到需要訪問(wèn)的URL和下載的文件名(數(shù)據(jù)庫(kù)獲取,jsp頁(yè)面顯示)。點(diǎn)擊事件JS如下:
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(); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SocketIo+SpringMvc實(shí)現(xiàn)文件的上傳下載功能
- SpringMVC下實(shí)現(xiàn)Excel文件上傳下載
- spring mvc實(shí)現(xiàn)文件上傳與下載功能
- SpringMVC+Ajax實(shí)現(xiàn)文件批量上傳和下載功能實(shí)例代碼
- SpringMVC實(shí)現(xiàn)文件上傳和下載功能
- 利用 FormData 對(duì)象和 Spring MVC 配合實(shí)現(xiàn)Ajax文件下載功能
- Spring MVC的文件上傳和下載以及攔截器的使用實(shí)例
- Springmvc實(shí)現(xiàn)文件下載2種實(shí)現(xiàn)方法
相關(guān)文章
java泛型的局限探究及知識(shí)點(diǎn)總結(jié)
在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于java泛型的局限探究及知識(shí)點(diǎn)總結(jié)內(nèi)容,有需要的朋友們可以跟著學(xué)習(xí)參考下。2021-07-07Java多線程執(zhí)行處理業(yè)務(wù)時(shí)間太久解決方法代碼示例
這篇文章主要介紹了Java多線程執(zhí)行處理業(yè)務(wù)時(shí)間太久解決方法代碼示例的相關(guān)資料,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12POI對(duì)Excel自定義日期格式的讀取(實(shí)例代碼)
下面小編就為大家?guī)?lái)一篇POI對(duì)Excel自定義日期格式的讀取(實(shí)例代碼)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-11-11scala 隱式轉(zhuǎn)換與隱式參數(shù)的使用方法
這篇文章主要介紹了scala 隱式轉(zhuǎn)換與隱式參數(shù)的使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11小議Java中final關(guān)鍵字使用時(shí)的注意點(diǎn)
final關(guān)鍵字代表著最后、不可改變,無(wú)論是在用final修飾類、修飾方法還是修飾變量時(shí),都要注意內(nèi)存分配的問(wèn)題.這里來(lái)小議Java中final關(guān)鍵字使用時(shí)的注意點(diǎn):2016-06-06關(guān)于SpringSecurity認(rèn)證邏輯源碼分析
這篇文章主要介紹了關(guān)于SpringSecurity認(rèn)證邏輯源碼分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07SpringBoot自定義starter啟動(dòng)器的實(shí)現(xiàn)思路
這篇文章主要介紹了SpringBoot如何自定義starter啟動(dòng)器,通過(guò)starter的自定義過(guò)程,能夠加深大家對(duì)SpringBoot自動(dòng)配置原理的理解,需要的朋友可以參考下2022-10-10java實(shí)現(xiàn)賬號(hào)登錄時(shí)發(fā)送郵件通知
這篇文章主要為大家詳細(xì)介紹了java如何實(shí)現(xiàn)在賬號(hào)登錄時(shí)發(fā)送郵件通知的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-09-09