前端文件上传与下载(含 base64流文件)

上传文件实现

  • elementUi el-upload + axios

    自定义上传实现:

    /**
    * 批量上传文件
    * @param {*} param
    */
    export function uploadFile(param, fileInfo) {
        return request({
            method: 'post',
            url: `document/hdfs/up`,
            data: param,
            onUploadProgress: (progressEvent) => {
            let num = progressEvent.loaded / progressEvent.total * 100 | 0;  //百分比
            fileInfo.onProgress({percent: num})     //进度条
            }
        });
    }
    
    
    
    // 自定义上传
    handleCustomUpload(fileInfo) {
      let file = fileInfo.file;
      this.handleUploadFile(file, fileInfo);
    },
    handleUploadFile(file, fileInfo) {
      // 执行具体上传代码
      let uploadFile = new FormData();
      uploadFile.append('file', file);
      let self = this;
      http.uploadFile(uploadFile, fileInfo)
      .then(res => {
        // 上传成功(打钩的小图标)
        fileInfo.onSuccess();
        if (res.items && (this.docDialogMode === '新增' || this.docDialogMode === '编辑' )) {
          self.docDialogForm.storagePath = res.items[0].storagePath;
          self.docDialogForm.name = res.items[0].name;
          self.docDialogForm.extension = res.items[0].name.slice(res.items[0].name.lastIndexOf('.') + 1);
        }
        if (res.items && this.docDialogMode === '批量上传') {
          self.docDialogForm.batchUploadFileInfo.push({
            name: res.items[0].name,
            storagePath: res.items[0].storagePath,
            extension: res.items[0].name.slice(res.items[0].name.lastIndexOf('.') + 1),
            uid: fileInfo.file.uid
          });
        }
      })
      .catch(() => {
        console.log('文件上传失败');
      })
    }
    
    • 上传文件转成 base64 二进制文件流上传
    function updateFile() {
        var fileInput = document.getElementById("selectFile");
        if(fileInput.files[0] == undefined){
            return;
        }
        var file = fileInput.files[0];
        //FileReader可直接将上传文件转化为二进制流
        var reader = new FileReader();  
        reader.readAsDataURL(file);//转化二进制流,异步方法
        reader.onload = function(){//完成后this.result为二进制流
            var base64Str = this.result;
            var startNum = base64Str.indexOf("base64,");
            startNum = startNum*1 + 7;
            //去除前部格式信息(如果有需求)
            var baseStr = base64Str.slice(startNum);
        }
    }
    

下载实现

你可能感兴趣的:(前端文件上传与下载(含 base64流文件))