zoukankan      html  css  js  c++  java
  • 原生js实现上传下载

    一、原生js做上传下载
    
    1、下载
    
    (1)、封装
    // 火狐浏览器等有兼容问题,点击没有反应
    const fileDownloadClick = (obj) => {
     if( document.all ){
      obj.click();
     } else {
      let event = document.createEvent("MouseEvents");
      event.initEvent('click', true, true);
      obj.dispatchEvent(event);
     }
    }
    const fileDownload = (res,obj) => {
      /*
      res 为接口返回的blob文件流
      obj :{}
     */
     
     let blob = new Blob([res]);
     let url = window.URL.createObjectURL(blob);
     let link = document.createElement('a');
     link.style.display = 'none';
     link.href = url;
     link.setAttribute('download', `${obj.userName || ' '}_${obj.weeklyTime || dateFormatYMD(new Date())}_${obj.weeklyType || '.xlsx' }`);
     document.body.appendChild(link);
     // link.click();
     fileDownloadClick(link);
     window.URL.revokeObjectURL(url);
    }
    
    (2)、使用
    a、请求头添加 responseType: 'blob',
    b、通过调用接口 fileDownload方法
    
    
    2、上传
    
    (1)、封装
    // html结构
    <input type="file" ref="upload" @change='handleUploadChange($event)' style="display:none;">
     
    // 触发选择图片的 事件
    handleUploadFile(row){ // 通过某一事件触发 
      this.$refs['upload'].click();
    }
    
    // 公共上传方法
    CommonUpload (e) {
      const files = e.target.files;
      let formData = new FormData();
      if(files && files[0]) {
        const file = files[0];
        // 对文件大小限制
        if(file.size > 1024 * 1024 *3) {
          alert('文件大小不能超过3M');
          return;
        } else {
          // 此处名字需要和后台对应, 暂定multipartFile
          formData.append("multipartFile", file); 
        }
      }
      // 为调用上传接口方法
      this.uploadFile_(formData)
    }
     
    // 调用
    async handleUploadChange(e){
      try {
        let res = await this.CommonUpload(e);
      }
     catch (err) {}
    }
    
    (2)、问题 当再次选择同一文件时,失效
    解决: ( 上传后执行下面 )
    this.$refs['upload'].value = ''; // 解决 input file 第二次失效的问题
     
    原因:
    input file value值为新选中的值,所以下次再选同一文件,不会触发change事件
    
    
    3、参数
    https://www.jb51.net/article/177841.htm
    
    
    参考
    https://blog.csdn.net/a545132569/article/details/96429178?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_baidulandingword-0&spm=1001.2101.3001.4242
  • 相关阅读:
    hdu1087Super Jumping! Jumping! Jumping!
    hdu1159Common Subsequence(最长公共子序列)
    hdu1069Monkey and Banana(最长递增子序列)
    poj2533(最长递增子序列)
    hdu1029Ignatius and the Princess IV
    uva10622(唯一分解定理)
    myeclipse设置技巧
    myeclipse2014新感悟
    小错误汇总
    字符串反转
  • 原文地址:https://www.cnblogs.com/-roc/p/14592237.html
Copyright © 2011-2022 走看看