前端文件上传与下载(含 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})     //进度条
        }
    });
}
<el-upload
ref="upload"
action=""
:http-request="handleCustomUpload"
:on-preview="handleFilePreview"
:on-remove="handleFileUploadRemove"
:on-success="handleFileUploadSuccess"
:before-upload="handleFileBeforeUpload"
:file-list="docDialogForm.fileList"
:multiple="docDialogMode === '批量上传' ? true : false"
:auto-upload="true"
>
// 自定义上传
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);
    }
}

下载实现
接口直接返回资源的访问路径

直接利用 <a> 标签下载

// 创建下载链接并开始下载
function createDownloadUrl(Url) {
    const a = document.createElement('a');
    a.style.display = 'none';
    a.download = '测试';
    a.href = Url;
    a.click();
    document.body.removeChild(a);
}

接口返回二进制文件流

使用 axios 下载

下载接口:

/**
* 下载文档
* @param {*} param
*/
export function downloadFile(documentCode) {
    return request({
        method: 'post',
        url: `document/hdfs/down?documentCode=${documentCode}`,
        responseType: 'blob'
    });
}

下载具体实现:

handleRowDownload(scope) {
    // 表格行下载
    http.downloadFile(scope.row.code)
    .then(res => {
        const blob = new Blob([res]);
        // 某些情况下需要明确下载的文件类型
        // const blob = new Blob([res], {type: "application/zip"});
        const a = document.createElement('a');
        a.download = scope.row.name;
        a.href = window.URL.createObjectURL(blob);
        a.click();
    })
    .catch(() => {
        this.$message.error('下载文档失败');
    })
}

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):