HeavenTang

导航

java读取resource下的文件 下载

点击查看代码
public void downloadKsxxYzyTemplate(HttpServletRequest request, HttpServletResponse response) {
        try {
//            FileDownloadUtils.downloadFileFromResource(response, YZYMB_NAME,YZYMB_URL);
            FileDownloadUtils.downloadFileFromResource(response,
                    "一志愿考生名单导入参考模板.dbf","/template/一志愿考生名单导入参考模板.dbf",
                    request);
        }catch (IOException e) {
            log.error("一志愿考生信息参考模板下载失败:{}",e);
            throw new ServiceException(2,"一志愿考生信息参考模板下载失败");
        }
    }

public static void downloadFileFromResource(HttpServletResponse response,
                                                String fileName,
                                                String classPathResourcePath,
                                                HttpServletRequest request) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(classPathResourcePath);
        if (!classPathResource.exists()) {
            throw new RuntimeException("找不到源文件!");
        }
        InputStream inputStream = classPathResource.getInputStream();
       /* response.setHeader("Content-Disposition", "attachment;filename=" +
                URLEncoder.encode(fileName, StandardCharsets.UTF_8.displayName()));
        response.setContentType("application/octet-stream");

        OutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
//        outputStream.close();
        inputStream.close();*/

//        ClassPathResource classPathResource = new ClassPathResource("/excel/机构导入模板.xlsx");
//        InputStream inputStream = classPathResource.getInputStream();
        //生成目标文件, 上面那种直接读取再输出dbf会打不开文件
        File somethingFile = File.createTempFile("Topic_Template", ".dbf");
        try {
            FileUtils.copyInputStreamToFile(inputStream, somethingFile);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        InputStream in = new FileInputStream(somethingFile);
        getFileContent(in, fileName, response, request);

    }

    public static  void getFileContent(InputStream inputStream, String name, HttpServletResponse response, HttpServletRequest request) {
        // 清空response
        response.reset();
        try {
            InputStream in = inputStream;
            response.setHeader("Content-Length", String.valueOf(in.available()));
            byte[] buffer = new byte[in.available()];
            //不加打开会文件损坏
            in.read(buffer);
            in.close();
            String userAgent = request.getHeader("User-Agent");
            /*String fileName;
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = URLEncoder.encode(name, "UTF-8");
            } else {
                // 非IE浏览器的处理:
                fileName = new String(name.getBytes("UTF-8"), "ISO-8859-1");
            }*/
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(name, StandardCharsets.UTF_8.displayName()));
            // 设置response的Header
//            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/x-dbf");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

前端:

点击查看代码
exportTemplate = () => {
    const { templateUrl } = this.props;
    certificateTemplate(templateUrl, {},{},(res) => {
        let fileName = res.headers['content-disposition'].split(';')[1].split('filename=')[1];
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display = 'none';
        const objectUrl = URL.createObjectURL(res.data);
        aLink.href = objectUrl;
        aLink.download = decodeURI(fileName);
        aLink.click();
        document.body.removeChild(aLink);
    });

// 模板
export function certificateTemplate(url, params, permission = auth.template,callback) {
    downloadFile(url, params, {headers:{permission}}).then(response=>{
        callback(response);
    }).catch(err=>{
        message.error("文件下载失败"+err);
    })
}

/**
 * add by ych
 * 下载文件,二进制流
 * @param {*} url 接口url
 * @param {*} params 查询参数
 * @param {*} config
 */
export function downloadFile(url, params, config = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, { responseType: 'blob', ...config })
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}

posted on 2024-02-27 10:38  HeavenTang  阅读(194)  评论(0编辑  收藏  举报