js 文件转base64上传服务器

HTML:

<input type="file"  (change)="onChange($event)"   value=" " id='fileUpload' >   / /  input会在页面上渲染成一个按钮,点击按钮,会打开本地文件夹, 重点在 type='file';

  

 
JS:
onChange(e){
      console.log(e);
      const file = e.srcElement.files[0]; // 获取从上传本地文件转换的数据
      const isJpgOrPng = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';  // 判断文件类型
      if (!isJpgOrPng) {
        this.message.error('You Can Only Upload Xlsx File!');
        return;
      }
      const data = {
        Base64: null,
        FileName: file.name
      };
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        data.Base64 = e.target['result']; // 获取文件装换后的Base64位文件
        data.Base64 = data.Base64.split('base64,')[1];  // Base64位文件获取时,不能直接传给后台,要将base64文件开头的前缀剔除,不然服务器会提示有中文字符,无法解析 
        this.apiService.post('XXXXXXX', data).subscribe(res => {
          if ( res.Result ) {
            this.message.create('success', 'Import Succeeded');
          }
        });
        // console.log(e.target.result);
      };
    }

  

原文地址:https://www.cnblogs.com/chenjiangyang/p/12758883.html