前後臺互動實現點選超連結通過指定的 url 去網路或者檔案伺服器下載檔案
阿新 • • 發佈:2018-11-09
前臺 VUE 介面:
<el-table-column prop="attachment" align="center" label="附件詳情"> <template slot-scope="scope"> <!--<el-button @click="downloadFile(scope.row.fileName,scope.row.fileUrl)">{{scope.row.fileName}}</el-button>--> <a @click="downloadFile(scope.row.fileName,scope.row.fileUrl)">{{scope.row.fileName}}</a> </template> </el-table-column>
//window.open開啟一個新的瀏覽器視窗,通過 url 對後臺的 rest 介面進行呼叫
downloadFile(fileName,fileUrl){ let param = {"fileUrl": fileUrl, "fileName": fileName}; window.open( downloadManage.downloadFile(param), this.openType ); },
/* 下載檔案,對引數 url 和 fileName 進行拼接處理,然後通過 window.open 對後臺的 rest 介面進行呼叫 */ export const downloadManage = { downloadFile: (query) => requestGetUrl('/process/downloadFile.do_', query, 'post'), };
後臺java程式碼:(rest介面,供前臺進行呼叫)
/** * 下載檔案 * * @return */ @RequestMapping("/downloadFile.do_") @ResponseBody public void downloadFile( HttpServletResponse response, @RequestParam String fileUrl, @RequestParam String fileName ) { downLoadFromUrl(fileUrl,fileName,response); } /** * 從網路Url中下載檔案 * @param urlStr 指定的url * @param fileName 下載檔案完成要叫的名字 * @param response */ public static void downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response){ try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //增加頭部,說明該檔案為附件,只能進行下載,不直接讀 response.setContentType("application/x-msdownload; charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); //得到輸入流 InputStream inputStream = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(inputStream); OutputStream os = response.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(os); /* ContentLength必須設定,否則檔案下載不全 * 或者呼叫 BufferedOutputStream#write(byte[] b, int off, int len) 方法輸出 */ response.setContentLength(bis.available()); byte[] b = new byte[1024]; while(bis.read(b) != -1) { bos.write(b); } bos.flush(); LOGGER.info("info:"+fileName+" download success"); } catch (IOException e) { LOGGER.error("uploadFile failed", e); } }
會出現如下通常我們網上點選某超連結下載檔案的效果:(下載完成出現在瀏覽器頁面左下角)