a标签实现文件下载(ie8可用)
生活随笔
收集整理的這篇文章主要介紹了
a标签实现文件下载(ie8可用)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景:項目中大量使用a標簽href屬性直接寫文件資源路徑,在火狐瀏覽器上可以直接使用,但是在ie8下則在瀏覽器直接打開,顯示為亂碼,為盡量減少修改,寫以下代碼。
?
js代碼
?
/*** 在頁面中引入該js文件:<%=PathUtil.jsLink("com.bop.web.fgwwjcommon", "/common/js/ie8-download-plug.js")%>* 頁面中a標簽的寫法:<a class="mini-button" href="/ResourceFiles/.../*.xls" iconCls="icon-download" >* 解決ie8下頁面中a標簽在href屬性直接寫文件路徑無法下載的問題,該插件只篩選后綴名為.xls/.xlsx/.rar/.doc/.docx/.pdf格式文件,* 需要添加其他文件格式請添加:[href$='.jpg'](以jpg格式為例,多個文件類型以英文逗號分隔,中間不得有空格)*/ replaceHref(); function replaceHref(){var a = $("[href$='.xls'],[href$='.xlsx'],[href$='.rar'],[href$='.doc'],[href$='.docx'],[href$='.pdf']");for (var i = 0; i < a.length; i++) {$(a[i]).attr("href","javascript:$.downloadTemplate('"+$(a[i]).attr("href")+"')");} } //文件下載 jQuery.downloadTemplate = function(filePath){jQuery('<form action="/fgwwjcommon/commonservice/downloadTemplate?theme=none" method="post">' + // action請求路徑及推送方法'<input type="text" name="filePath" value="'+filePath+'"/>' + // 文件名稱及文件路徑'</form>').appendTo('body').submit().remove(); };
java代碼
?
?
@Actionpublic void downloadTemplate() {HttpServletResponse response = ActionContext.getActionContext().getHttpServletResponse();HttpServletRequest resquest = ActionContext.getActionContext().getHttpServletRequest();String filePath = resquest.getParameter("filePath");String resourcePath = System.getProperty("resourceFiles.location");filePath = filePath.replace("/ResourceFiles", resourcePath);try {// path是指欲下載的文件的路徑。File file = new File(filePath);// 取得文件名。String fileName = file.getName();// 特殊處理火狐瀏覽器中文亂碼問題。String agent = resquest.getHeader("USER-AGENT");if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {fileName = "=?UTF-8?B?" + (new String(Base64.getEncoder().encode(fileName.getBytes("UTF-8")))) + "?=";} else {fileName = java.net.URLEncoder.encode(fileName, "UTF-8");}// 以流的形式下載文件。InputStream fis = new BufferedInputStream(new FileInputStream(filePath));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();// 設置response的Headerresponse.setContentType("text/html;charset=UTF-8");response.addHeader("Content-Disposition", "attachment;filename=" + fileName);response.addHeader("Content-Length", "" + file.length());OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");toClient.write(buffer);toClient.flush();toClient.close();} catch (IOException ex) {ex.printStackTrace();}}?
?
?
?
?
總結
以上是生活随笔為你收集整理的a标签实现文件下载(ie8可用)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简单定义一个RMB类
- 下一篇: micropython 播放音乐_用 p