将图像从Angular4上传到Cloudinary

时间:2017-06-28 06:35:59

标签: angular image-uploading cloudinary

我是cloudinary和Angular4的新手。

我一直在寻找一种通过Angular4将图像上传到cloudinary的方法,但还没有能够找到任何文档。我发现的文档与图像转换有关,而不是上传。

如何从Angular4上传图像到cloudinary。

PS。我正在使用Angular4 AOT

1 个答案:

答案 0 :(得分:1)

您可以找到示例here。它正在使用ng2-file-upload,它也适用于Angular4。

要考虑的要点是您的Cloudinary帐户wiring the uploader -

// Create the file uploader, wire it to upload to your account
const uploaderOptions: FileUploaderOptions = {
  url: `https://api.cloudinary.com/v1_1/${this.cloudinary.config().cloud_name}/upload`,
  // Upload files automatically upon addition to upload queue
  autoUpload: true,
  // Use xhrTransport in favor of iframeTransport
  isHTML5: true,
  // Calculate progress independently for each uploaded file
  removeAfterUpload: true,
  // XHR request headers
  headers: [
    {
      name: 'X-Requested-With',
      value: 'XMLHttpRequest'
    }
  ]
};
this.uploader = new FileUploader(uploaderOptions);

this.uploader.onBuildItemForm = (fileItem: any, form: FormData): any => {
  // Add Cloudinary's unsigned upload preset to the upload form
  form.append('upload_preset', this.cloudinary.config().upload_preset);
  // Add built-in and custom tags for displaying the uploaded photo in the list
  let tags = 'myphotoalbum';
  if (this.title) {
    form.append('context', `photo=${this.title}`);
    tags = `myphotoalbum,${this.title}`;
  }
  form.append('tags', tags);
  form.append('file', fileItem);

  // Use default "withCredentials" value for CORS requests
  fileItem.withCredentials = false;
  return { fileItem, form };
};