`
qinjingkai
  • 浏览: 259863 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

java中的文件下载

阅读更多

             开发中文件上传做得多了,文件下载都是第一次遇到;原理就是往后台的输出流写入文件的内容,现总结如下:

 public void downLoad(String filePath, String contentType) throws Exception {
        // System.out.println(filePath);
        File f = new File(filePath);
        if (!f.exists()) {
            res.sendError(404, "对不起,下载文件没有找到,无法下载!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        //res为请求对应的HttpServletResponse对象
        res.reset(); // 非常重要
        res.setContentType(contentType + ";charset=utf-8");
        res.setHeader("Content-Disposition", "attachment; filename="
                + f.getName());
        OutputStream out = res.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.flush();
        out.close();

    }

 

 

至于   res.setContentType(contentType + ";charset=utf-8"); 中setContentType的值根据不同的文件类型不同有相应不同的写法 对应关系大体如下:

 

(注:如果文件后缀名为avi则写  res.setContentType("video/avi") )

avi-----video/avi
bmp-----application/x-bmp
doc-----application/msword
gif-----image/gif
htm或者html-----text/html
jpg或者jpeg-----image/jpeg
mht或者mhtml-----message/rfc822
mp3-----audio/mp3
ppt-----application/vnd.ms-powerpoint
pptx-----application/vnd.openxmlformats-officedocument.presentationml.presentation
rm-----application/vnd.rn-realmedia
rmvb-----application/vnd.rn-realmedia-vbr
xls-----application/x-xls
xml-----text/xml
rar-----application/octet-stream
zip-----application/x-zip-compressed
swf-----application/x-shockwave-flash
wav-----audio/wav
txt-----text/plain
excel/zip:data/Application    

分享到:
评论
2 楼 shujun62 2011-01-14  
1 楼 yiminghe 2009-04-18  
注意一下: 你这样做 文件名是中文的话浏览器会显示文件名称乱码的,需要转化编码为 iso8859-1,浏览器才能正确识别

相关推荐

Global site tag (gtag.js) - Google Analytics