编程技术文章分享与教程

网站首页 > 技术文章 正文

下载文件工具类 文件下载工具是什么

hmc789 2024-11-08 19:44:19 技术文章 2 ℃

一、创建下载工具类

@Slf4j
public class Down {

     /**
     * 
     * @param response
     * @param downLoadPath 下载文件的路径
     * @param realName 文件名字
     */
    public static void downLoad(HttpServletResponse response,String downLoadPath,String realName) {
        File file=new File(downLoadPath);
        try {
            common(response, realName, file);
        } catch (IOException e) {
            log.error("IO异常",e);
        } finally {
            file.delete();
        }
    }

    private static void common(HttpServletResponse response, String realName, File file) throws IOException {
        InputStream ins = new FileInputStream(file);
        response.setCharacterEncoding("utf-8");
        response.setHeader("pragma", "No-Cache");
        response.setHeader("Cache-Control", "No-Cache");
        response.setDateHeader("Expires", 0);
        //multipart/form-data
        response.setContentType("multipart/form-data;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+new String(realName.getBytes("GB2312"), "ISO8859-1"));
        Cookie fileDownload=new Cookie("fileDownload", "true");
        fileDownload.setPath("/");
        response.addCookie(fileDownload);
        OutputStream os=response.getOutputStream();
        byte[] buff = new byte[2048];
        int len;
        while ((len=ins.read(buff))>0) {
            os.write(buff, 0, len);
        }
        os.flush();
        os.close();
        ins.close();
    }
}
标签列表
最新留言