servlet实现下载

来源:互联网 发布:js获取json数组长度 编辑:程序博客网 时间:2024/06/16 16:53

本来之前写一个servlet文件下载的,会出现很多问题,英文下载可以,中文下载就出现了乱码或者没显示的情况;

经过优化,封装成了一个工具类,如果有更好的,还劳烦赐教。

测试代码文件结构:
这里写图片描述

package Tool;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.UnsupportedEncodingException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DownloadTool {    /**     * 直接可以利用本工具进行文件下载     *      * @param request           传入servlet中的     * @param response          传入servlet中的     * @param dir               WebRoot下面的目录,如果是WebRoot/download只需要写 download     * @param fileName          文件的名字请包含后缀名     */    public static void down(HttpServletRequest request,            HttpServletResponse response, String dir, String fileName) {        // 发送头文件,告诉浏览器调用下载功能        try {            response.setHeader("Content-Disposition", "attachment;filename="+                    new String(fileName.getBytes("utf-8"),"ISO-8859-1"));        } catch (UnsupportedEncodingException e1) {            e1.printStackTrace();        }        // 获取绝对路径        String path = "/" + dir + "/" + fileName;        String realPath = request.getSession().getServletContext()                .getRealPath(path);        System.out.println("realPath:"+realPath);        File file = new File(realPath);        if (file.exists()) {//文件存在才开始下载            try {                FileInputStream fis = new FileInputStream(file);                ServletOutputStream sos = response.getOutputStream();                byte[] buff = new byte[1024];                int len = 0;                while ((len = fis.read(buff)) != -1) {                    sos.write(buff, 0, len);                }                // 关闭io流                sos.close();                fis.close();            } catch (FileNotFoundException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        }    }}
1 0
原创粉丝点击