使用javascript将png上传到imgur

djq*_*djq 6 javascript png imgur

我正在尝试使用Javascript上传pngimgur.我直接使用了Imgur API 示例中的代码,但我不认为我正在传递png文件,因为我收到一条错误消息file.type is undefined.我认为该文件没问题,因为我尝试了几个不同的png.我的代码如下:

<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> 
Run Code Online (Sandbox Code Playgroud)

png文件test.png存储在与我的html文件相同的目录中.

Juh*_*nen 2

您使用的示例期望您使用输入元素(类型=文件)上传一些图像。试试这个例子您可以使用这样的Canvas 访问图像数据。

总而言之,您需要执行以下操作:

  1. 使用您的文件创建新图像(需要位于本地域中)
  2. 加载时将图像绘制到画布上
  3. 使用该方法提取图像数据
  4. 像这里一样将该数据传递给 imgur