简体   繁体   English

cloudinary javascript图像上传空白文件

[英]cloudinary javascript image uploads a blank file

i am using javascript to upload an image using the unsigned mode. 我正在使用javascript使用无符号模式上传图像。 the resultant image is a blank image or i can say an image filled with black color. 生成的图像是空白图像,或者我可以说是充满黑色的图像。 not sure what is wrong. 不知道出什么问题了。 the code looks like follow: 该代码如下所示:

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));

resultant image is: 结果图像为:

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

Please note that imgData is base64 encoded 请注意,imgData是base64编码的

You need to use FormData for uploading the file: 您需要使用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);
}

See full example here . 在这里查看完整示例。 It will upload a small Michael Jordan jumpman image to your account. 它将一个小迈克尔·乔丹(Michael Jordan)跳人图像上传到您的帐户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM