博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaWeb下载文件response
阅读量:6294 次
发布时间:2019-06-22

本文共 6234 字,大约阅读时间需要 20 分钟。

以下代码在 chrome、firefox,安卓自带手机浏览器上测试通过,但未经过完全测试,先记录下

public static void downLoadFile(HttpServletRequest request,HttpServletResponse response,String fullPath,String fileName) throws IOException {        OutputStream outp = response.getOutputStream();        File file = new File(fullPath);        if (file.exists()) {            response.setContentType("APPLICATION/OCTET-STREAM");         //response.setContentType("application/octet-stream; charset=utf-8");            String filedisplay = fileName;            String agent = (String)request.getHeader("USER-AGENT");                          if(agent != null && ( agent.indexOf("MSIE") != -1 || agent.indexOf("Trident") != -1 || agent.indexOf("Mobile") != -1 )) {                   //移动浏览器 或 ie  Trident是标识是ie浏览器 特别处理ie11 的问题                filedisplay=URLEncoder.encode(filedisplay,"utf-8");                System.out.println("下载文件,移动设备浏览器 或 ie[" + filedisplay + "]");                  response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);            } else {
         //其他浏览器 String enableFileName = "=?UTF-8?B?" + (new String(Base64.getBase64(filedisplay))) + "?="; System.out.println("下载文件,其他浏览器[" + enableFileName + "]"); response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName); } FileInputStream in = null; try { outp = response.getOutputStream(); in = new FileInputStream(fullPath); byte[] b = new byte[1024]; int i = 0; while ((i = in.read(b)) > 0) { outp.write(b, 0, i); } outp.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { in.close(); in = null; } if (outp != null) { outp.close(); outp = null; response.flushBuffer(); } } } else { outp.write("文件不存在!".getBytes("utf-8"));        outp.close(); } }

 

/**     * 获取下载文件的content-type类型。     *      * @param extName  文件后缀     * @return     */    private String getContextType(String extName, boolean isRead) {        String contentType = "application/octet-stream";        if ("jpg".equalsIgnoreCase(extName) || "jpeg".equalsIgnoreCase(extName)) {            contentType = "image/jpeg";        } else if ("png".equalsIgnoreCase(extName)) {            contentType = "image/png";        } else if ("gif".equalsIgnoreCase(extName)) {            contentType = "image/gif";        } else if ("doc".equalsIgnoreCase(extName) || "docx".equalsIgnoreCase(extName)) {            contentType = "application/msword";        } else if ("xls".equalsIgnoreCase(extName) || "xlsx".equalsIgnoreCase(extName)) {            contentType = "application/vnd.ms-excel";        } else if ("ppt".equalsIgnoreCase(extName) || "pptx".equalsIgnoreCase(extName)) {            contentType = "application/ms-powerpoint";        } else if ("rtf".equalsIgnoreCase(extName)) {            contentType = "application/rtf";        } else if ("htm".equalsIgnoreCase(extName) || "html".equalsIgnoreCase(extName)) {            contentType = "text/html";        } else if ("swf".equalsIgnoreCase(extName)) {            contentType = "application/x-shockwave-flash";        } else if ("bmp".equalsIgnoreCase(extName)) {            contentType = "image/bmp";        } else if ("mp4".equalsIgnoreCase(extName)) {            contentType = "video/mp4";        } else if ("wmv".equalsIgnoreCase(extName)) {            contentType = "video/x-ms-wmv";        } else if ("wm".equalsIgnoreCase(extName)) {            contentType = "video/x-ms-wm";        } else if ("rv".equalsIgnoreCase(extName)) {            contentType = "video/vnd.rn-realvideo";        } else if ("mp3".equalsIgnoreCase(extName)) {            contentType = "audio/mp3";        } else if ("wma".equalsIgnoreCase(extName)) {            contentType = "audio/x-ms-wma";        } else if ("wav".equalsIgnoreCase(extName)) {            contentType = "audio/wav";        }        if ("pdf".equalsIgnoreCase(extName) && isRead)// txt不下载文件,读取文件内容        {            contentType = "application/pdf";        }        if (("sql".equalsIgnoreCase(extName) || "txt".equalsIgnoreCase(extName)) && isRead)// pdf不下载文件,读取文件内容        {            contentType = "text/plain";        }        return contentType;    }

 

其他参考,但未经验证

http 下载文件时,中文文件名在firefox下乱码的问题,一般在http header中是这样操作的:"Content-Disposition","attachment;filename=文件名.xx"其实,按照  rfc231 , Content-Disposition 应该按照如下格式设置:"Content-Disposition","attachment;filename*=utf-8'zh_cn'文件名.xx"只要严格按照标准设置以后,自然在各种浏览器下都会正常运行了.

 

String userAgent = request.getHeader("User-Agent");    String rtn = "";    try {        String new_filename = URLEncoder.encode(fileName, "UTF8");        // 如果没有UA,则默认使用IE的方式进行编码,因为毕竟IE还是占多数的        rtn = "filename=\"" + new_filename + "\"";        if (userAgent != null) {            userAgent = userAgent.toLowerCase();            // IE浏览器,只能采用URLEncoder编码            if (userAgent.indexOf("msie") != -1) {                rtn = "filename=\"" + new_filename + "\"";            }            // Opera浏览器只能采用filename*            else if (userAgent.indexOf("opera") != -1) {                rtn = "filename*=UTF-8''" + new_filename;            }            // Safari浏览器,只能采用ISO编码的中文输出            else if (userAgent.indexOf("safari") != -1) {                rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";            }            // Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出            else if (userAgent.indexOf("applewebkit") != -1) {                new_filename = MimeUtility.encodeText(fileName, "UTF8", "B");                rtn = "filename=\"" + new_filename + "\"";            }            // FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出            else if (userAgent.indexOf("mozilla") != -1) {                rtn = "filename*=UTF-8''" + new_filename;            }        }    } catch (UnsupportedEncodingException e) {        e.printStackTrace();    }    return rtn;

 

转载地址:http://lhpta.baihongyu.com/

你可能感兴趣的文章
MYSQL——常用运算符和函数
查看>>
JS获取上传文件的大小
查看>>
Shell脚本调用mysql语句
查看>>
远程连接服务器的方法:
查看>>
docker入门
查看>>
linux下如何判断oracle数据库tns是否设置正常
查看>>
dell物理服务器硬件磁盘监控
查看>>
sqlserver的事务回滚和设置事务保存点操作
查看>>
https搭建(openssl)
查看>>
CISCO上ADSL配置的方法
查看>>
队列实现qq解密
查看>>
制作RPM包
查看>>
mysql多实例脚本
查看>>
python文件操作举例
查看>>
Outlook 2003命令行参数开关详解
查看>>
mysql中文乱码问题的解决方案
查看>>
Redhat7开机图形或文字界面
查看>>
Linux state 方式 安装nginx 服务
查看>>
LNMP(php-fpm的pool,慢执行日志,定义open_bashdir,php-fpm进程管理
查看>>
Flask rst 文档转换为html格式文件
查看>>