【问题标题】:cloudinary javascript image uploads a blank filecloudinary javascript图像上传一个空白文件
【发布时间】:2017-08-22 08:05:51
【问题描述】:

我正在使用 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 编码的

【问题讨论】:

    标签: javascript cloudinary


    【解决方案1】:

    上传文件需要使用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。它会将迈克尔乔丹跳人小图片上传到您的帐户。

    【讨论】:

      猜你喜欢
      • 2015-12-19
      • 2019-05-24
      • 2020-04-07
      • 2021-03-20
      • 2020-03-02
      • 2021-11-18
      • 2012-02-06
      • 2021-04-18
      • 2017-03-08
      相关资源
      最近更新 更多