JAVA浏览器response导出文件

后端,写出一个流给out

/**
     * 导出文件到客户端
     *
     * @param zipFile
     * @param fileName
     * @param response
     * @throws IOException
     */
    public void exportFile(File zipFile, String fileName, HttpServletResponse response) throws IOException {
        InputStream fis = null;
        OutputStream outputStream = null;
        try {
            // 定义文件的输入流
            fis = new BufferedInputStream(new FileInputStream(zipFile));
            // 定义一个缓冲区
            byte[] buffer = new byte[fis.available()];
            // 把流写入byte缓冲区
            fis.read(buffer);
            // 关闭文件流
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            // 防止中文乱码
            String finalFileName = new String(fileName.getBytes("GBK"), "ISO8859-1");
            // 设值返回文件属性,浏览器会根据属性调用下载文件方法
            response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
            // 设值文件大小属性,浏览器用于判断文件是否写完
            response.addHeader("Content-Length", "" + zipFile.length());
            // 前端获取文件名,需要解码
            response.addHeader("downLoadName", URLEncoder.encode(fileName, "UTF-8"));
            // 定义输出流
            outputStream = new BufferedOutputStream(response.getOutputStream());
            // 定义输出类型为二进制流输出
            response.setContentType("application/octet-stream");
            // 把流写入response
            outputStream.write(buffer);
            // flush落盘
            outputStream.flush();
            // 关闭输出流
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
 /**
     * 导出文件到客户端
     *
     * @param zipFile
     * @param fileName
     * @param response
     * @throws IOException
     */
    public void exportFile(File zipFile, String fileName, HttpServletResponse response) throws IOException {
        // 定义文件的输入流
        InputStream fis = new BufferedInputStream(new FileInputStream(zipFile));
        // 定义一个缓冲区
        byte[] buffer = new byte[fis.available()];
        // 把流写入byte缓冲区
        fis.read(buffer);
        // 关闭文件流
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        // 防止中文乱码
        String finalFileName = new String(fileName.getBytes("GBK"), "ISO8859-1");
        // 设值返回文件属性,浏览器会根据属性调用下载文件方法
        response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
        // 设值文件大小属性,浏览器用于判断文件是否写完
        response.addHeader("Content-Length", "" + zipFile.length());
        // 前端获取文件名,需要解码
        response.addHeader("downLoadName", URLEncoder.encode(fileName, "UTF-8"));
        // 定义输出流
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        // 定义输出类型为二进制流输出
        response.setContentType("application/octet-stream");
        // 把流写入response
        outputStream.write(buffer);
        // flush落盘
        outputStream.flush();
        // 关闭输出流
        outputStream.close();
    }

注意:前端接收流信息,浏览器导出,前端要接收二进制流,否则,前端返回一堆乱码

//VUE写法
api.getTaskDownLoad(_params).then(
                res => {
                    console.log(res)
                    this.loading = false
                    const data = res.data // 这里填内容的字符串
                    const blob = new Blob([data], { type: "application/octet-stream" })
                    //const blob = new Blob([data], {type: 'audio/wav'})
                    const a = document.createElement("a")
                    a.href = URL.createObjectURL(blob)
                    a.download = res.headers.downloadname
                    a.click()
                    URL.revokeObjectURL(a.href)
                    a.remove();
                    //window.open(res.sourceFileUrl, "_blank");
                },
                err => {
                    this.loading = false
                    this.$Message.error('获取报告失败');
                }
            )

export function getTaskDownLoad (params) {
    return fetch({
        url: url.host + 'vehicle/dataStatisticsTask/downLoad',
        method: 'post',
        //添加 blob属性,否则压缩文件损坏
        responseType: 'blob',
        params,
        contentType:'application/json;application/octet-stream'
    })
}

return new Promise((resolve, reject) => {
    axios({
      method: options.method || 'post',
      url: options.url,
      data:data,
      // 添加 blob属性,否则压缩文件损坏
      responseType: options.responseType,
      headers: {
        'currentUser': JSON.stringify(currentUser),
        'Content-type':options.contentType || 'application/x-www-form-urlencoded'//'multipart/form-data'
      },
      timeout: 2 * 60 * 1000
    }).then(res => {
      if(res.headers.hasOwnProperty("downloadname")){
        res.headers.downloadname=decodeURIComponent(res.headers.downloadname)
        resolve(res)
      }
      resolve(res.data);
    }).catch(error => {
      console.error('接口请求异常:' + error);
      reject(error);
    });
  });
//JS写法
$('#btn_export').click(function () {
                var url = G.context_root+"/vehicle/vehBusAddHydrogen/detail/export";
                var turnForm = document.createElement("form");
                document.body.appendChild(turnForm);
                turnForm.method = 'GET';
                turnForm.action = url;
                turnForm.target = '_blank';
                var busID = document.createElement("input");
                busID.setAttribute("name", "bus.id");
                busID.setAttribute("type", "hidden");
                busID.setAttribute("value", '${busId}');
                turnForm.appendChild(busID);
                var begin = document.createElement("input");
                begin.setAttribute("name", "beginTime");
                begin.setAttribute("type", "hidden");
                begin.setAttribute("value",  $("#beginTime").val());
                turnForm.appendChild(begin);
                var end = document.createElement("input");
                end.setAttribute("name", "endTime");
                end.setAttribute("type", "hidden");
                end.setAttribute("value",  $("#endTime").val());
                turnForm.appendChild(end);
                turnForm.submit();

猜你喜欢

转载自blog.csdn.net/xionglangs/article/details/115543114