zoukankan      html  css  js  c++  java
  • fetch下载文件--统一拦截导出文件(含JAVA)

    批量选择文件,通过后台打包形成流文件提供给前端下载,一般我们request.js都会做一些验证与报错提示,但是不支持文件下载。

    而文件下载中,前端的解决方法可以通过响应头的Content-Type来判断。

    直接上代码:

    export async function apiBatchSave (params) {
      return fetch(`${API_DOC_JAVA}/batchSave`,{
        method: 'POST',
        headers: {
          'Accept': 'application/json, */*',
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'cache': 'default',
          'x-ajax': 'true'
        },
        'credentials': 'include', //表示请求是否携带cookie
        body: formartBody(params)
      }).then(function (response) {
        if (response.ok) {
          response.blob().then((blob) => {
            const a = window.document.createElement('a');
            const downUrl = window.URL.createObjectURL(blob);// 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
            const filename = response.headers.get('Content-Disposition').split('filename=')[1].split('.');
            a.href = downUrl;
            a.download = `${decodeURI(filename[0])}.${filename[1]}`;
            a.click();
            window.URL.revokeObjectURL(downUrl);
          });
          return {state: 1}
        } else {
          throw new Error('')
        }
      })
    }


    java后端配置

     public void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName){
            try{
                response.setContentType("application/x-msdownload");
                response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(zipName, "utf-8"));
    
                ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
                BufferedOutputStream bos = new BufferedOutputStream(zos);
    
                for(Map.Entry<String, byte[]> entry : files.entrySet()){
                    String fileName = entry.getKey();            //每个zip文件名
                    byte[]    file = entry.getValue();            //这个zip文件的字节
    
                    BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
                    zos.putNextEntry(new ZipEntry(fileName));
    
                    int len = 0;
                    byte[] buf = new byte[10 * 1024];
                    while( (len=bis.read(buf, 0, buf.length)) != -1){
                        bos.write(buf, 0, len);
                    }
                    bis.close();
                    bos.flush();
                }
                bos.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
  • 相关阅读:
    [转]SP 2010: How To – Event Receivers and Custom Error Pages
    sharepoint ServerTemplate values
    SPSiteDataQuery不完全使用手册(转)
    jQuery EasyUI 提示框(Messager)用法
    单选按钮 点击value值自动把单选按钮选中
    easy ui tabs 顶部绑定事件
    jquery 中的 $("#id") 与 document.getElementById("id") 的区别
    jquery ajax 的data 存表单的值
    JSP中用include标签动态引入其它文件报错
    Js获取当前日期时间及其它操作
  • 原文地址:https://www.cnblogs.com/TLSF/p/10475409.html
Copyright © 2011-2022 走看看