2013-06-05 55 views
2

我在imgur.com註冊了一個應用程序(匿名用法),並且我得到了一個應用程序密鑰。我在這裏使用它:imgur api鍵不工作從JavaScript?

self.uploadImage = function(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(); // I wrote about it: https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/ 
     fd.append("image", file); // Append the file 
     fd.append("key", "<my key>"); // Get your own key http://api.imgur.com/ 
     var xhr = new XMLHttpRequest(); // Create the XHR (Cross-Domain XHR FTW!!!) Thank you sooooo much imgur.com 
     xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom! 
     xhr.onload = function() { 
      // reference side-specific class here 
      document.querySelector("#image-uploaded-one-" + self.cardId()).href = JSON.parse(xhr.responseText).upload.links.imgur_page; 

     } 
     // Ok, I don't handle the errors. An exercice for the reader. 

     /* And now, we send the formdata */ 
     xhr.send(fd); 
    }; 

如果我用我的鑰匙,我得到一個錯誤說Cannot read property 'links' of undefined,但是如果我用一個我在教程中,一切正常。我前幾天創建了這個密鑰,所以我不認爲時間是問題。它還能是什麼?

我認爲問題是工作的關鍵是由api的v2產生的,而新的關鍵是v3,它不適用於指定的v2。如果我指定v3,我會得到「HTTP訪問被禁用,請求必須使用ssl。」我怎樣才能得到這個工作?

+1

嘗試這樣做的console.log(JSON.parse(xhr.responseText)),以查看響應是什麼與你的鑰匙。你看到的錯誤是他們發送了成功的消息,但除了上傳對象之外。 –

+0

@AaronSaray我在解析的responseText中得到「invalid api key」:/ – SB2055

回答

3

下面的代碼固定它:

self.uploadImage =函數(文件){

 /* 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(); // I wrote about it: https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/ 
     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() { 
      var response1 = JSON.parse(xhr.responseText); 
      var response = JSON.parse(xhr.responseText).data.link; 
      document.querySelector("#image-uploaded-one-" + self.cardId()).href = response; 

     } 
     // Ok, I don't handle the errors. An exercice for the reader. 
     xhr.setRequestHeader('Authorization', 'Client-ID <yourkey>'); 

     /* And now, we send the formdata */ 
     xhr.send(fd); 
    };