其他分享
首页 > 其他分享> > 读取本地文件并下载(来自马一鸣)

读取本地文件并下载(来自马一鸣)

作者:互联网

// 马一鸣
@RequestMapping(value = "/excelOut")
public void excelStandardmplateOut(HttpServletRequest request,
HttpServletResponse response) throws IOException{
URL save = Thread.currentThread().getContextClassLoader().getResource("");
String str = save.toString();

    str=str.substring(5,str.length());
    str=str.replaceAll("%20", " ");
    int num = str.lastIndexOf("myhr-healthcare");//项目名,应用到不同的项目中,这个需要修改!
    str=str.substring(0, num+"myhr-healthcare".length());

    str = str +"/src/main/resources/static/职工医疗互助保障(权限配置)导入模板.xlsx";//Excel模板所在的路径。
    File f = new File(str);
    // 设置response参数,可以打开下载页面
    response.reset();
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    try {
        response.setHeader("Content-Disposition", "attachment;filename="+ new String(("职工医疗互助保障(权限配置)导入模板" + ".xlsx").getBytes(), "iso-8859-1"));//下载文件的名称
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    ServletOutputStream out = response.getOutputStream();
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(new FileInputStream(f));
        bos = new BufferedOutputStream(out);
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (final IOException e) {
        throw e;
    } finally {
        if (bis != null){
            bis.close();
        }
        if (bos != null){
            bos.close();
        }
    }
}

标签:读取,本地,bos,马一鸣,bis,str,new,null,response
来源: https://www.cnblogs.com/yxyuanxiang/p/15342174.html