javascript - cloudinary javascript图像上传一个空白文件

标签 javascript cloudinary

我正在使用 JavaScript 以未签名模式上传图像。生成的图像是空白图像,或者我可以说是填充黑色的图像。不知道出了什么问题。代码如下:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://api.cloudinary.com/v1_1/mycloud/image/upload", false);
xhttp.setRequestHeader("Content-type", "application/json");

xhttp.onreadystatechange = function() { //Call a function when the state changes.
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    alert(xhttp.responseText);
  } else {
    alert("Error dude: " + xhttp.statusText);
  }
}

var parameters = {
  "file": imgData,
  "upload_preset": "mycode"
};

xhttp.send(JSON.stringify(parameters));

结果图像是:

http://res.cloudinary.com/viksphotography/image/upload/v1490752341/irgvt7b3qwoug1vz7own.jpg

请注意,imgData 采用 Base64 编码

最佳答案

您需要使用FormData来上传文件:

const cloudName = 'your cloud name';
const unsignedUploadPreset = 'your unsigned upload preset';

// Upload base64 encoded file to Cloudinary
uploadFile('data:image/gif;base64,R0lGODlhSAFIAf....');

// *********** Upload file to Cloudinary ******************** //
function uploadFile(file) {
  var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
  var xhr = new XMLHttpRequest();
  var fd = new FormData();
  xhr.open('POST', url, true);
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

  xhr.onreadystatechange = function(e) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      // File uploaded successfully
      var response = JSON.parse(xhr.responseText);
      // https://res.cloudinary.com/cloudName/image/upload/v1483481128/public_id.jpg
      var url = response.secure_url;
      // Create a thumbnail of the uploaded image, with 150px width
      var tokens = url.split('/');
      tokens.splice(-2, 0, 'w_150,c_scale');
      var img = new Image(); // HTML5 Constructor
      img.src = tokens.join('/');
      img.alt = response.public_id;      
      document.body.appendChild(img);
    }
  };

  fd.append('upload_preset', unsignedUploadPreset);
  fd.append('tags', 'browser_upload'); // Optional - add tag for image admin in Cloudinary
  fd.append('file', file);
  xhr.send(fd);
}

查看完整示例 here 。它将上传一张迈克尔·乔丹的 Jumpman 小图片到您的帐户。

关于javascript - cloudinary javascript图像上传一个空白文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43083283/

相关文章:

javascript - 无法让简单的 jquery ajax 调用工作

javascript - 为网页编写动画标题的最有效方法是什么?

laravel - 在本地存储图像 vs cloudinary vs s3

jquery - Cloudinary 上传小部件与 "Failed to set the ' 上的 Jquery 'HTMLInputElement' value' 属性“

node.js - 无法将图像上传到cloudinary

javascript - 使用 JavaScript 更改背景后 CSS 背景样式停止工作

javascript - 将字符串转换为数组中的日期对象

javascript - AWS Elastic Beanstalk : How to change node command ? 在最近的更新中删除了容器选项?

javascript - 图像对象只能记录到控制台

image-manipulation - 如何替换 cloudinary 中的图像并保持相同的 URL?