使用 Cloudinary 的 Post API 上传图片,但不使用 Cloudinary SDK

3

我刚接触Cloudinary和Angular。我一直在寻找一种上传图片到Cloudinary的方式,但不希望使用SDK,因为Cloudinary提供了使用post API上传图片的选项。我尝试了下面的方法,但没有成功。

uploadImage(event) {
var that = this;
this.create_blob(event.srcElement.files[0], function (blob_string) {
  that.http.post('https://api.cloudinary.com/v1_1/image/upload/', { file: blob_string}).subscribe(res => {
    // url of upload file
  })
});

}

 create_blob(file, callback) {
var reader = new FileReader();
reader.onload = function () { callback(reader.result) };
reader.readAsDataURL(file);}

我在控制台中得到了以下错误信息。

HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "https://api.cloudinary.com/v1_1/image/upload/", ok: false}
2个回答

3

根据您提供的代码,我可以看到以下几点:

  • 您可以检查响应头,查找一个名为X-Cld-Error的标头,其中会提供有关请求失败原因的更多信息。在这种情况下,我期望它返回cloud_name is disabled。当通过云端交付URL请求资源并出现错误时,此标头也存在。例如: https://res.cloudinary.com/demo/image/upload/ww_350/sample.jpg 将返回包含Invalid transformation parameter - wwX-Cld-Error标头。

  • 这与下一个问题有关,您使用的上传API端点不包括您的云名称。应该是 https://api.cloudinary.com/v1_1/<cloud name>/image/upload

  • 客户端上传(即没有身份验证签名的上传)需要设置一个未签名的上传预设,在上传的同时将其作为两个必填参数之一提供。上传预设提供了定义上传参数的方法,这些参数通常可以在使用签名的上传调用中直接设置。当不使用签名时,许多这些参数无法指定,并且如果需要,应在上传预设中进行配置。您可以在此文档的此部分中了解更多信息,包括如何创建上传预设: https://cloudinary.com/documentation/upload_images#unsigned_upload


1
您在提交请求时忘记添加cloud_name,这是一个小错误。您可以通过访问Cloudinary仪表板来找到您的cloud_name。正确的代码如下所示。
    uploadImage(event) {
    var that = this;
    this.create_blob(event.srcElement.files[0], function (blob_string) {
    that.http.post('https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/image/upload/', { file:  blob_string}).subscribe(res => {
    // url of upload file
  })

注意:以下方法是使用未签名的方式上传,因此当您尝试下载图像时,其URL将以"http"而不是"https"开头。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接