美文网首页VueJS
vue + axios文件下载

vue + axios文件下载

作者: webmrxu | 来源:发表于2018-09-26 20:51 被阅读915次

文件上传是很简单的解决了,可文件下载可真是难到我了。

在开发过的前后端分离项目中,有开发过angular4 版本的文件下载功能,使用文件流 blob 的方式下载文件是没有问题的,可是在vue + axios 的版本是死活下载不了,blob 二进制数据当做字符串进行了处理。返回 response 如下:

1537363236(1).jpg

查看angualr4 版本的文件下载,同一个文件,下载的内容是一样的,但angualr4 版本的文件下载,response 自动处理成了blob 对象;

先展示下angualr版本 文件下载的前后端代码:

angular版本前端代码:

    //文件下载
    public download(docFile){
        let docIds : string[]=[];
        docIds.push(docFile.docId);
        this.http.doGet({
            url:'/doc/docs',
            search:{
                "attachId": this.attachId,
                "docIds" : docIds
            },
            responseType : ResponseContentType.Blob,
            success:(req,res) =>{
                let fileName = docFile.docName 
                if(window.navigator.msSaveOrOpenBlob){
                    // 兼容ie11
                    var blobObject = new Blob([res.result]); 
                    window.navigator.msSaveOrOpenBlob(blobObject, fileName); 
                }else{
                    let url = URL.createObjectURL(new Blob([res.result]));
                    let a = document.createElement('a');
                    document.body.appendChild(a); //此处增加了将创建的添加到body当中
                    a.href = url;
                    a.download = fileName;
                    a.target = '_blank';
                    a.click();
                    a.remove(); //将a标签移除
                }   
            }
        })
    }  

angular版本后端代码:

/**
 * @throws Exception @Description: 1、前端界面必须转入attachId
 *         2、根据附件编号进行下载,下载与附件有关的文件(将附件有关的多个附件打包压缩进行下载处理) @param attachId:
 *         1、不为空,且docIds有值,则下载附件对应的文档(可能多个)进行压纹后传到前端 2、 如果docIds没有值,则下载附件所有的文档 docIds:
 *         1、如果attachId为空,此值必须有值,此值也为空,则异常 2、 如果attachId为空时, 此值如果是一个文档id,则直接下载 3、
 *         如果是多个文档ID,则会根据文档ID下载对应的文件,并压缩返回给前台 @return 输出流到前台 @throws
 */
@GetMapping("/docs")
public ResponseEntity<byte[]> download(String attachId, String[] docIds, RedirectAttributes attr) throws Exception {
    DataParamBean fileBean = docManagerService.sDownLoadFile(attachId, docIds);
    HttpHeaders headers = getHeader(fileBean.getFileName());
    try {
        System.err.println(fileBean.getFile().toString());
        //Tool.FILE.forceDelete(fileBean.getFile());
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(fileBean.getFile()), headers, HttpStatus.OK);
    } catch (Exception e) {
        attr.addAttribute("msgInfo", e.getMessage());
    }
    return null;
}

返回debugger response 内容如下:

angular.jpg

angular http 处理后如下:

before.jpg

上图可以看出,angular http 处理后,response 的内容直接转换成了 blob 对象

再次debugger axios 的response 如下图:直接当做字符串处理了,感觉像是乱码

axios.jpg

经过不断的调试,最终选择了另一种方式进行文件下载。使用iframe,汗... 不是很优雅,先解决紧急问题,后期在调试和优化查找解决方案:

2018-12-12 更新,使用node 和 xhr 调试 文件上传和下载
在这篇文章中,调试使用原生的xhr 调试发现,xhr.responseType = "blob"; 属性设置后,浏览器就处理了返回数据,把流处理成了 blob 对象,前端不用再处理返回数据,也不用转换数据为流数据。

步骤1:在index.html 文件新建iframe标签

iframe.jpg

步骤2:在vue methos 中添加函数, 使用form进行提交 docId 文档id 和 token 会话

downloadByPath(path, name) {
      const fields = [
        {
          name: 'docName',
          value: name,
        },
        {
          name: 'path',
          value: path
        },
        {
          name: '_token',
          value: sessionStorage.getItem('Admin-Token')
        }
      ];
      const form = document.createElement('form');
      form.action = process.env.BASE_API + '/docmanager/download';
      form.mehod = 'GET';
      form.target = 'downloadFrame';

      for (let i = 0, l = fields.length; i < l; i++) {
        const field = fields[i];
        const f = document.createElement('input');
        f.type = 'hidden';
        f.name = field.name;
        f.value = field.value;
        form.appendChild(f);
      }
      document.body.appendChild(form);
      form.submit();
      document.body.removeChild(form);
    },

步骤3: 修改后端代码

/**
 * 单个附件下载功能 contrle 层
 */
@GetMapping("/download")
@AccessStrategy(value = Strategy.ANY)
public ResponseEntity<byte[]> download(String path, String docName, String _token, HttpServletResponse response) throws Exception {
    boolean result = docManagerService.sDownLoadFile(path,docName,response);
    if(!result) {
        Throws.throwException(Codes._100002, "附件不存在");
    }
    return null;
}

/**
 * 文件下载公共服务类 ,下载指定的文档编号的的文档  server 层
 */
boolean sDownLoadFile(String path,String docName,HttpServletResponse response) throws Exception{
    boolean result = false;
    BufferedOutputStream bos = null;
    InputStream is = null;
    String ftpFileName = path.substring(path.lastIndexOf("/")+1);//FTP服务器保存的文件名
    response.setContentType("application/octet-stream;charset=UTF-8");
    response.addHeader("Content-Disposition", "attachment;filename="+ new String(docName.getBytes("UTF-8"), "ISO8859-1"));
    try{
        int reply;
        ftpClient.setControlEncoding(encoding);
        ftpClient.connect("127.0.0.1",21);
        ftpClient.login("Administrator", "watermelon");
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        // 获取ftp登录应答代码
        reply = ftpClient.getReplyCode();
        // 验证是否登陆成功
        if(!FTPReply.isPositiveCompletion(reply)){
            ftpClient.disconnect();
            return result;
        }
        path = path.replace("\\", "/");
        path = new String(path.getBytes(encoding),"iso-8859-1");
        if(path.contains(".")){
            ftpFileName = path.substring(path.lastIndexOf("/")+1);
            path = path.substring(0,path.lastIndexOf("/"));
        }
        boolean isSuccess = ftpClient.changeWorkingDirectory(path);
        if(isSuccess){
            FTPFile[] fs = ftpClient.listFiles();
            for(FTPFile ff : fs){
                if(ff.getName().equals(ftpFileName)){
                    is = ftpClient.retrieveFileStream(ff.getName());
                    
                    StreamUtils.copy(is, response.getOutputStream());
                    break;
                    
                }
            }
            ftpClient.logout();
            result = true;
        }else{
            return result;
        }
    }catch(Exception e){
        e.printStackTrace();
        throw e;
    }finally{
        try{
            if(bos != null){
                bos.close();
            }
            if(is != null){
                is.close();
            }
            if(ftpClient.isConnected()){
                ftpClient.disconnect();
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    return result;
}

相关文章

  • vue + axios文件下载

    文件上传是很简单的解决了,可文件下载可真是难到我了。 在开发过的前后端分离项目中,有开发过angular4 版本的...

  • 2018-09-26传参 和axion

    传参 axios 下载:npm install axios版本1.0:vue-resource2.0:axios(...

  • 路由

    传参 axios 下载:npm install axios版本1.0:vue-resource2.0:axios(...

  • axios

    下载:npm install axios版本1.0:vue-resource2.0:axios(相当于库)Vue中...

  • Vue Axios

    axios: vue中的ajax,是用来前后端交互的 npm install axios 下载axios 建立数据...

  • vue3配置axios

    一、安装 vue add axios执行上述命令会在plugins文件夹生成axios.js文件 二、axios.js

  • Vue axios解决跨域问题

    首先 vue init webpack axios初始化一个vue文件 然后安装 npm i axios -S 引...

  • VUE关于Axios的配置

    安装axios 1.通过vue ui引入2.手敲 axios文件结构 axios:存放axios实例 getEnv...

  • vue axios下载文件(axios post/get方式下载

    导语: 当你点进这篇文章说明你的http基础很烂,该去补http的知识了. 网上搜了一堆根本就不好使,都是JQ...

  • VUE、Axios、AJAX、POST文件下载

网友评论

    本文标题:vue + axios文件下载

    本文链接:https://www.haomeiwen.com/subject/jsbjoftx.html