imgurl上的xhr-html文件上传给出了错误的请求

xhr html file upload on imgurl gives bad request

本文关键字:错误 请求 上的 xhr-html 文件 imgurl      更新时间:2023-09-26

我想使用imgur的API上传一张图片到imgur;使用javascript(node.js)。我总是得到这样的回应:

{"数据":{"错误":"不支持图像格式,或图像已损坏。","请求":"/3/upload","方法":"POST"},"成功":false,"状态":400}

这是我写的代码:

ImgUrlHelper = 
{
InitUploadValidateFile :function(element)
{
     var file = element.value;
     if(file === "")
        return;
     if(file != '')
     { 
         var valid_extensions = /(.jpg|.jpeg|.gif|.png)$/i;   
          if(valid_extensions.test(file))
          {
                console.log("ok");
                this.Upload(file);
          }
          else
                console.log("notok");
     }
     else
        console.log("notok");
},           
Upload: function(file) {
    var fd = new FormData(); 
    fd.append("image", file); 
    var xhr = new XMLHttpRequest(); 
    xhr.open("POST", "https://api.imgur.com/3/upload", true); 
    xhr.onload = this.OnLoad;
    xhr.onerror = this.OnNetworkError;
    xhr.onreadystatechange = this.OnReadyStateChange;
    xhr.onprogress= this.OnProgress;
    xhr.setRequestHeader('Authorization', 'Client-ID xxxxxxxxxxxx');
    xhr.send(fd);
},
OnReadyStateChange:function(xhr){
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        var link = JSON.parse(xhr.responseText).data.link;
        console.log(link);    
    }
    if(xhr.status != 200)
    {
        console.log(xhr.status);

        //log error
    }
},
OnNetworkError:function(xhr)
{
    //log error
    console.log("network error while uploading.");
    console.log(xhr);
},
OnProgress : function(e)
{
    if (e.lengthComputable) {
      var percentComplete = (e.loaded / e.total) * 100;
      console.log(percentComplete + '% uploaded');
    }
},
OnLoad :  function(res) {
}
}

我通过在输入type="file"上使用onchange事件来调用它:

onchange="ImgUrlHelper.InitUploadValidateFile(this)"

我认为在读取我用文件上传控制选择的文件时出现了问题,这里是:

fd.append("image", file); 

此时,文件包含字符串:"C:''fakepath''img.jpg"。我可能真的需要对图像进行编码吗?

您应该上传File对象,而不是字符串。

var file = element.value;更改为var file = element.files[0];:

// assuming that element is an <input type=file>
InitUploadValidateFile: function(element) {
    var file = element.files[0];
    if (!file)
        return;
    var valid_extensions = /('.jpg|'.jpeg|'.gif|'.png)$/i;
    if (valid_extensions.test(file.name)) {
        console.log("ok");
        this.Upload(file);
    } else {
        console.log("notok");
    }
},