angular - 上传文件到 S3 但返回 observable

标签 angular amazon-s3 file-upload

我如何确保以下方法返回可观察值?

  uploadFile(file, filename) {
    const contentType = file.type;
    const bucket = new S3(
      {
        accessKeyId: environment.awsAccessKeyId,
        secretAccessKey: environment.awssecretAccessKey,
        region: environment.awsRegion
      }
    );
    const params = {
      Bucket: environment.awsBucket,
      Key: environment.awsKey + filename,
      Body: file,
      ACL: 'public-read',
      ContentType: contentType
    };

    bucket.upload(params, function (err, data) {
      if (err) {
        this.logger.debug('There was an error uploading your file: ', err);
        return null;
      }
      this.logger.debug('Successfully uploaded file.', data);
      return data;
    });
  }

我想按如下方式从组件中调用它并捕获返回输出:

  this.ngxLoader.start();
  this.uploadService.uploadFile(newFile, sermonName), ((data) => {
    if (data) {
      // this.sermon.id = data.id;
      // this.logger.debug(`Posted file: ${JSON.stringify(data)}`);
      // this.logger.debug(`Updating file id: ${JSON.stringify(this.sermon.id)}`);
      // this.update();
      this.ngxLoader.stop();
    }
  }, error => {
    this.ngxLoader.stop();
    this.modalService.displayMessage('Oops!', error.message);
  });

最佳答案

将结果/错误返回为 Observable


return Observable.create(observer => {
  bucket.upload(params, function (err, data) {
    if (err) {
      this.logger.debug('There was an error uploading your file: ', err);
      observer.error(err);
    }
    this.logger.debug('Successfully uploaded file.', data);
    observer.next(data);
    observer.complete();
  });
});

更改以处理组件中的结果/错误


this.uploadService.uploadFile(newFile, sermonName)
.subscribe(
  data => {
    if (data) {
      // this.sermon.id = data.id;
      // this.logger.debug(`Posted file: ${JSON.stringify(data)}`);
      // this.logger.debug(`Updating file id: ${JSON.stringify(this.sermon.id)}`);
      // this.update();
      this.ngxLoader.stop();
    }
  }, 
  error => {
    this.ngxLoader.stop();
    this.modalService.displayMessage('Oops!', error.message);
  });

当然我们需要导入下面的内容。

import { Observable } from 'rxjs';

还为函数添加显式返回以进行类型检查。

uploadFile(file, filename): Observable<any> {

关于angular - 上传文件到 S3 但返回 observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56328640/

相关文章:

angular - Elasticsearch 和 Angular 2

angular - 在 Angular CLI 中从 ng-build 中排除模块......不工作

amazon-web-services - AWS S3 CLI 中的选择性文件下载

java - 优化大量小文件的 S3 下载

python - 如何使用 S3 Select 和制表符分隔的 csv 文件

c# - 通过 POSTMAN 发送时 HttpRequest.Files 为空

python - Django / python : Change uploaded filename before saving file

javascript - KeyboardEvent 的 Angular 4 单元测试

javascript - HTTP 状态代码 401,即使我在请求中发送凭据

ios - Xamarin iOS后台上传任务(iOS 7)——DidFinishEventsForBackgroundSession