javaweb实现文件下载(包含.txt文件等默认在浏览器中打开的文件)

文件下载 

刚开始研究文件下载是找有关js的方法,找了好多发现对于.txt、.xls等文件在浏览器中还是打开,或者就是跨域问题。后来通过查找资料发现可以在后台对http相应头设置参数,而且实现起来也不复杂。现总结如下:

文章参考 《javaweb文件下载》、《根据网络url 实现web下载图片 java》、《Java文件下载及web文件的contentType大全

前端代码:

function downloadLog(logName){
	location.href=basePath + "/demp/common/downloadDeviceLog.do";
}

后台代码:

import org.apache.commons.io.IOUtils;

    @RequestMapping({"/demp/common/downloadDeviceLog.do"})
    @ResponseBody
    public void downloadDeviceLog(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String logUrl = "https://**/2018-11-20.txt";
        try {
            String [] logUrlArray = logUrl.split("/");
            String fileName = logUrlArray[logUrlArray.length-1];
            URL url = new URL (logUrl);
            URLConnection uc = url.openConnection();
            response.setContentType("application/octet-stream");//设置文件类型
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Length", String.valueOf(uc.getContentLength()));
            ServletOutputStream out = response.getOutputStream();
            IOUtils.copy(uc.getInputStream(), out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注:

1、其中关键的一句是给响应头设置“content-disposition”属性,关于它的介绍可参考文章《Content-Disposition 响应头,设置文件在浏览器打开还是下载

2、contenType也可以设置成专门针对某种文件类型的,比如文中是.txt类型,就可以这样设置:

response.setContentType("text/plain");//设置文件类型

未完待续。。。。

猜你喜欢

转载自blog.csdn.net/tao111369/article/details/84308917
今日推荐