2012-02-12 49 views
6

我正在尝试使用Javascript上传pngimgur。我直接使用Imgur API example的代码,但我不认为我正在传递png文件,因为我收到一条错误消息,说file.type is undefined。我认为该文件是可以的,因为我已经尝试了几个不同的PNG。我的代码如下:使用javascript上传PNG到imgur

<html> 
<head> 
<script type="text/javascript"> 
function upload(file) { 
    // file is from a <input> tag or from Drag'n Drop 
    // Is the file an image? 
    if (!file || !file.type.match(/image.*/)) return; 

    // It is! 
    // Let's build a FormData object 
    var fd = new FormData(); 
    fd.append("image", file); // Append the file 
    fd.append("key", "mykey"); // Get your own key: http://api.imgur.com/ 

    // 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() { 
     // Big win! 
     // The URL of the image is: 
     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); 
} 
</script> 
</head> 

<body> 

<button type="button" onclick="upload('test.png')">upload to imgur</button> 

</body> 
</html> 

png文件test.png存储在同一目录作为我的HTML文件。

回答

2

您正在使用的示例希望您使用输入元素(type = file)来上传某个图像。尝试this example。您可以使用Canvas like this访问图像数据。

总之,你需要这样做:

  1. 创建文件新的图像(必须是本地域)
  2. 在onload事件
  3. 提取图像绘制到一个Canvas使用this method
  4. 传递数据imgur like here
+0

感谢您的建议的图像数据。为了将图像添加到画布上,是否是图像'id'?我假设我不能使用文件名来引用它,基于@ skimberk1的评论。 – djq 2012-02-12 15:53:38

+0

使用文件名无法引用图像。您需要将其加载到img元素,然后使用drawImage将其内容加载到画布。在img的onload处理程序中完成后面的部分很重要。否则它将无法工作。 – 2012-02-12 16:09:27

+0

感谢bebraw,这有助于我理解流程。我正在尝试http://html2canvas.hertzen.com/;它看起来会执行这些步骤的一部分。 – djq 2012-02-12 16:34:53

3

该文件必须是用HTML5 fileAPI创建的File对象,您不能只给它一个文件名并期望它能够正常工作。

Javascript无法访问文件系统,它只能访问使用拖放或文件输入提供给它的文件。