Imgur API错误,如何使用XHR上传

1my*_*myb 3 javascript jquery xmlhttprequest imgur

    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);
Run Code Online (Sandbox Code Playgroud)

上面的代码是我用来通过phonegap上传图像文件的代码.但后来我猜测代码已过时,可以使用最新的imgur API.由OAuth支持.我可以知道如何修复它以上传图像吗?

poz*_*444 5

你是对的...代码已经过时,所以我修复的方法是按照以下说明匿名上传图像:

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

对于你的代码我也假设你使用了Drag'n Drop的例子,所以函数应该是这样的:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

希望能帮助到你!!