a标签实现文件文件下载(ie8可用)

来源:互联网 发布:淘宝直通车分时折扣 编辑:程序博客网 时间:2024/06/05 18:21

背景:项目中大量使用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代码

@Action    public 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();            // 清空response            response.reset();            // 设置response的Header            response.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();        }    }


原创粉丝点击