2013-04-11 43 views
3
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); 

上面的代碼是我用來通過手機上傳圖像文件的代碼。但後來我猜代碼已經過時了,可以使用最新的imgur API。它由OAuth支持。我可以知道如何修復它以便上傳圖像嗎?Imgur API錯誤,如何用XHR上傳

回答

5

你說得對......的代碼已經過時,所以我固定的方法是按照以下說明匿名上傳圖片:

1.-在FormData,你只需要在圖像追加,所以不應該附加密鑰

2.-您必須發送一個包含您的客戶端ID的標頭,我假設您已擁有該標頭......我使用以下代碼執行此操作xhr.setRequestHeader('Authorization', 'Client-ID FOO'); 根據文檔,它必須是在打開XMLHttpRequest之後但在發送請求之前。

3,當你試圖獲得鏈接,你必須解析JSON,以讀取信息,鏈接進來名爲linkdata節點,以便解析是: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下降的例子,因此函數應該是這個樣子:

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

我鼓勵你看看到documentation,這是非常友好和幫助你做出的功能和東西......正如我所說的這是匿名上傳,如果你想上傳圖片的用戶,你必須先認證用戶和密碼,使用令牌,refresh'em,我didn這樣做,但它不應該太複雜,一旦你瞭解它是如何工作的...

希望它有幫助!