2013-06-05 76 views
0

我正在嘗試編寫一些讓用戶上傳文件到imgur的JavaScript。對我來說,第一步是從我的web服務器(公開可用)加載一個圖像,然後嘗試使用我的api密鑰上傳圖像。這是我到目前爲止有:使用javascript上傳到imgur

self.uploadImage = function upload(file) { 
     debugger; 
     file = $.get("../../Content/images/icon.png", function() { 
      alert("success"); 
     }) 
     .done(function() { alert("second success"); }) 
     .fail(function() { alert("error"); }) 
     .always(function() { alert("finished"); }); 

     // file is from a <input> tag or from Drag'n Drop 
     // Is the file an image? 

     if (!file || !file.type.match(/image.*/)) return; // fails here 

     // It is! 
     // Let's build a FormData object 

     var fd = new FormData(); 
     fd.append("image", file); // Append the file 
     fd.append("key", "<my key>"); 

     // Create the XHR 
     var xhr = new XMLHttpRequest(); 
     xhr.open("POST", "http://api.imgur.com/2/upload.json"); 
     xhr.onload = function() { 
      // The URL of the image is: 
      JSON.parse(xhr.responseText).upload.links.imgur_page; 
     }; 

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

我不能讓過去的第一個if聲明雖然 - 我得到那個說

Uncaught TypeError: Cannot call method 'match' of undefined

我得到從不用彷徨成功的警報錯誤。 ..我不知道如何進一步調試,因爲我對js有點新...任何幫助將不勝感激。

的if語句:

enter image description here

+0

'file.type'的值是什麼?或者更好的是,'typeof file.type'是什麼? – SomeShinyObject

+0

@ChristopherW我得到的typeof file.type是「undefined」,typeof文件是「object」 - 我會截圖 – SB2055

+0

有你的答案。 'match'是一個字符串方法。 – SomeShinyObject

回答

0

看來file.type是不確定的。原因是您正在錯誤地使用jQuery.get函數的返回值。該函數返回一個jqXHR對象,該對象不具有type屬性。

+0

但它應該被定義...因此我的問題 – SB2055

+0

是什麼讓你覺得它應該被定義?我無法在jqXHR對象的jQuery文檔中找到此屬性。 – Chris

+0

文件在我的代碼的第三行中定義...我遵循這個:https://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/ – SB2055