如何使用Cloudinary / Angular(5)和Ionic(3)将图像作为签名请求上传?

时间:2018-11-02 10:38:58

标签: ionic-framework cloudinary

Cloudinary有一个basic.js示例,我正在我的Ionic / Angular项目中尝试实现。

问题是,出于某种原因,“ @ cloudinary / angular-5.x”的离子版本始终使用unsigned_upload功能,我希望能够之前对其进行转换我上传的内容与Cloudinary示例相同。

要进行转换,需要signed上传而不是unsigned上传。

由于存在许多版本,并且大多数示例不起作用,因此我的是:

Ionic: 3
Angular: 5.2.11

Cloudinary: 
"cloudinary": "^1.11.0",
"cloudinary-core": "^2.5.0",
"@cloudinary/angular-5.x": "^1.0.2"

basic.js

我的配置位于{en {1}}

中提到的结构的.env变量中。
cloudinary.config

我可以使用以下代码将其上传 unsigned

未签名的离子请求

var dotenv = require('dotenv');
dotenv.load();

var fs = require('fs');
var cloudinary = require('cloudinary').v2;

// set your env variable CLOUDINARY_URL or set the following configuration
/*cloudinary.config({
  cloud_name: '',
  api_key: '',
  api_secret: ''
});*/

var url = "http://res.cloudinary.com/demo/image/upload/couple.jpg"
cloudinary.uploader.upload(url,{"tags":"basic_sample","width":500,"height":500,"crop":"fit","effect":"saturation:-70"} ,
  function(err,image){
   if (err){ 
    console.warn(err);
    return;
   }

   console.log("* "+image.public_id);
   console.log("* "+image.url);

   // Transform image
   cloudinary.url(image.public_id, 
    {
      width: 200,
      height: 150,
      crop: "fill",
      gravity: "face",
      radius: 10,
      effect:"sepia",
      format: "jpg"
      }
    ));
  });

离子签名的请求

因此,要转换图像,我需要使用名为ngOnInit(): void { const uploaderOptions: FileUploaderOptions = { url: 'https://api.cloudinary.com/v1_1/' + this.cloudinary.config().cloud_name + '/upload', autoUpload: false, isHTML5: true, removeAfterUpload: true, headers: [{ name: 'X-Requested-With', value: 'XMLHttpRequest' }] }; this.uploader = new FileUploader(uploaderOptions); // Add custom tag for displaying the uploaded photo in the list this.uploader.onBuildItemForm = (fileItem: any, form: FormData): any => { form.append('upload_preset', this.cloudinary.config().upload_preset); form.append('public_id', 'subfolder/' + this.UUID); form.append('file', fileItem); fileItem.withCredentials = false; return { fileItem, form }; }; } 的参数

eager

但是随后出现以下错误

form.append('eager', 'c_crop,w_191,h_145,g_face,z_0.7');

当我删除预设以“告诉”它可能是已签名的请求时,出现上述错误+ Upload completed with status code 400 { "message": "Eager parameter is not allowed when using unsigned upload. Only upload_preset,callback,public_id,folder,tags,context,face_coordinates,custom_coordinates,source upload parameters are allowed. }

所以我不确定我该如何“告诉”它-使用签名的请求,并从Upload preset must be specified when using unsigned upload.env等那里获取我的配置...

1 个答案:

答案 0 :(得分:1)

对于签名上传,您需要创建一个签名。在发布请求期间,您必须将其附加在表单中。

签名是SHA1十六进制字符串,由时间戳记(unixtime),public_id(任何文本)和您的cloudinary API_SECRET组成。

这是我可行的示例

private generateSignature() {
    this.public_id = `image_${Date.now()}`; // I like to make it unique.
    this.unixtime = Date.now() / 1000 | 0;
    return CryptoJS.SHA1(`public_id=${this.public_id}&timestamp=${this.unixtime}${this.API_SECRET}`).toString()
}

在这里,我使用CryptoJS进行抄写。

在发送API请求之前,将此签名附加到表单主体。 例如

 initFileUploader(): void {
    const self = this;
    self.uploader = new FileUploader({            
        url: 'https://api.cloudinary.com/v1_1/your_cloud_name/upload',
        allowedMimeType: ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'],
        maxFileSize: 524288,//512 KB
        autoUpload: true,
        removeAfterUpload: true,
        isHTML5: true,
        headers: [
            {
                name: 'X-Requested-With',
                value: 'XMLHttpRequest'
            }
        ]
    });
    self.uploader.onAfterAddingFile = (file) => {
        file.withCredentials = false;
    };

    self.uploader.onSuccessItem = (item, response, status) => {
        const resp = <any>JSON.parse(response);
        if (resp) {
            this.onSuccess.emit(resp);
        } else {
            this.onError.emit('An error occured during upload. Please retry');
        }
    };

    self.uploader.setOptions(self._uploaderOptions);

    self.uploader.onBuildItemForm = (fileItem: any, form: FormData): any => {
        let signature = this.generateSignature();

        form.append('timestamp', this.unixtime.toString());
        form.append('public_id', this.public_id);
        form.append('api_key', this.API_KEY); //your cloudinary API_KEY
        form.append('signature', signature);

        return { fileItem, form };
    };                
}

我使用ng2-file-upload上传...