Imgur API错误,如何用XHR上传

Imgur API Error, How to upload with XHR

本文关键字:何用 XHR 上传 API 错误 Imgur      更新时间:2023-09-26
    var fd = new FormData();
    fd.append("image", file); // Append the file
    fd.append("key", API_KEY);
    // Create the XHR (Cross-Domain XHR FTW!!!)
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
    xhr.onload = function() {
        console.log(JSON.stringify(xhr.responseText));
        alert("Anything?");
        var img_url = JSON.parse(xhr.responseText).upload.links.original;
        console.log("Image url of the uploaded image" + img_url);

上面的代码是我用来通过phonegap上传图像文件的代码。但我猜代码是过时的,不能与最新的imgur API一起工作。由OAuth支持。我可以知道如何修复它,以便上传图像吗?

你是对的…代码是过时的,所以我固定的方式是匿名上传图像与以下说明:

1。-在FormData中,你只需要附加图像,所以键不应该附加

2。-你必须发送一个带有你的客户端id的标题,我想你已经有了…我用下面的代码xhr.setRequestHeader('Authorization', 'Client-ID FOO');来做根据文档,它必须在打开XMLHttpRequest之后,但在发送请求之前。

3。-当你试图获得链接时,你必须解析JSON以便读取信息,链接来自data节点,名称为link,因此解析将是:var link = JSON.parse(xhr.responseText).data.link;

4。-你必须使用OAuth 2.0的新稳定API,所以你上传图像的行应该看起来像这样:xhr.open("POST", "https://api.imgur.com/3/image.json");…正如你所看到的,它只是改变了数字,这是版本,而不是upload,它使用image,它必须是https…供您参考,这是第一种建议的方法,另一种建议的方法,也有效,如下:xhr.open("POST", "https://api.imgur.com/3/upload.json");

对于你的代码,我也假设你使用了拖放的例子,所以函数应该看起来像这样:
function upload(file) {
    /* Is the file an image? */
    if (!file || !file.type.match(/image.*/)) return;
    /* It is! */
    document.body.className = "uploading";
    /* Lets build a FormData object*/
    var fd = new FormData(); 
    fd.append("image", file); // Append the file
    var xhr = new XMLHttpRequest(); // Create the XHR (Cross-Domain XHR FTW!!!) Thank you sooooo much imgur.com
    xhr.open("POST", "https://api.imgur.com/3/image.json"); // Boooom!
    xhr.onload = function() {
    // Big win!    
        var link = JSON.parse(xhr.responseText).data.link;
        document.querySelector("#link").href = link;
        document.querySelector("#link").innerHTML = link;

        document.body.className = "uploaded";
    }
    // Ok, I don't handle the errors. An exercice for the reader.
    xhr.setRequestHeader('Authorization', 'Client-ID FOO');
    /* And now, we send the formdata */
    xhr.send(fd);
}

我鼓励你看一下文档,它非常友好,帮助你创建函数和东西…正如我所说的,这是匿名上传,如果你想用用户上传图像,你必须先用用户和密码进行身份验证,使用令牌,并刷新它们,我没有这样做,但一旦你了解了它是如何工作的,它应该不会太复杂…

希望有帮助!!