码迷,mamicode.com
首页 > 编程语言 > 详细

java中如何设置下载文件

时间:2016-10-13 01:52:53      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

如果想要设置某一url为下载文件的方法如下

需要设置文件响应类型,使用response.setContentType,比如jpeg格式的图片。如果想要访问该页面时出现下载保存的窗口,使用response.setHeader("Content-Disposition", "attachment;filename="+filename.getName())函数。也可以是pdf文件,或者其他格式的,如果想要查找浏览器可以识别什么格式的文件,需要到服务器的配置文件中找,比如tomcat服务器中搜索mime-mapping即可查看浏览器是别的文件类型。

 

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setCharacterEncoding("utf-8");
        
        File filename = new File("D:\\chengxu\\ML\\2.jpg");
        response.setContentType("image/jpeg");
        response.setHeader("Content-Disposition", "attachment;filename="+filename.getName());
        
        OutputStream out = response.getOutputStream();
        
        FileInputStream fileinput = new FileInputStream(filename);
        
        byte[] charbuffer = new byte[1024];
        int length = 0;
        while ((length=fileinput.read(charbuffer))!=-1) {
            out.write(charbuffer, 0, length);
        }
        
    }

 

java中如何设置下载文件

标签:

原文地址:http://www.cnblogs.com/zhaopengcheng/p/5954599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!