【问题标题】:Store file to MinIO from browser form (Angular2)将文件从浏览器表单存储到 MinIO (Angular2)
【发布时间】:2020-02-18 20:50:00
【问题描述】:

我正在做一个 Angular8 应用程序的原型,它可以将文件从表单上传到 MinIO。 这是表格:

上传-form.component.html:

<input class="form-control" type="file" (change)="onFileChanged($event)" required />
<button mat-flat-button color="primary" class="flex__item--middle u-1/3 u-mt+" type="sumbit">
    Upload
</button>

这里是ts:

上传-form.component.ts

onFileChanged(event) {
    let reader = new FileReader();
    if(event.target.files && event.target.files.length) {
      const [file] = event.target.files;

      this.uploadForm.patchValue({
        fileName: file.name,
        fileSize: file.size
      });

      
    
      reader.onload = () => {
        this.uploadForm.patchValue({
          fileStream: reader.result
        });
        reader.readAsDataURL(file);
      };
    }
  }
  
  // ... here is the service call 
  // this.uploadService.sendMinIO(form_values).then(...

这里是对 MinIO putObject 函数的 API 调用:

minioClient.putObject(bucketName, fileName, fileStream, fileSize, function (err, etag).

Angular 服务不相关,因为它只是将数据原封不动地传递。

使用这种方法,文件被创建和存储,但内容是我从 FileReader 获得的 base64 编码字符串。我尝试了几种方法来获取文件内容。

MinIO wait for a "stream" (Readable Stream) 所以我尝试使用 Buffer (new Buffer(string, "base64").... 或 streamifier 和其他技巧,但我认为这里有一些我不明白的基本内容。

如何将来自 Angular 的数据存储到 MinIO 的初始文件中?

【问题讨论】:

    标签: angular file-upload base64 minio


    【解决方案1】:

    您应该在服务器中删除readAsDataURL(查看 API 文档中的注释)在 base64 编码字符串中添加的标头。例如:

    const { file } = req.body; // the base64 encoded string
    const buffer = Buffer.from(file.replace(/^data:image\/\w+;base64,/, ""),'base64');
    

    如果文件是图像(png、jpeg)或:

    const buffer = Buffer.from(file.replace(/^data:application\/pdf;base64,/, ""),'base64');
    

    如果文件是pdf文档,然后添加到bucket中:

    minioClient.putObject('bucket', 'filename', buffer)
    

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 2015-08-08
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 2022-01-05
      • 2019-10-10
      • 1970-01-01
      相关资源
      最近更新 更多