你說得對......的代碼已經過時,所以我固定的方法是按照以下說明匿名上傳圖片:
1.-在FormData
,你只需要在圖像追加,所以不應該附加密鑰
2.-您必須發送一個包含您的客戶端ID的標頭,我假設您已擁有該標頭......我使用以下代碼執行此操作xhr.setRequestHeader('Authorization', 'Client-ID FOO');
根據文檔,它必須是在打開XMLHttpRequest
之後但在發送請求之前。
3,當你試圖獲得鏈接,你必須解析JSON,以讀取信息,鏈接進來名爲link
的data
節點,以便解析是: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這樣做,但它不應該太複雜,一旦你瞭解它是如何工作的...
希望它有幫助!