使用javascript将png上载到imgur

使用javascript将png上载到imgur,javascript,png,imgur,Javascript,Png,Imgur,我正在尝试使用Javascript将png上传到。我直接使用了Imgur API中的代码,但我认为我没有正确地传递png文件,因为我收到一条错误消息,说file.type未定义。我认为该文件是好的,因为我已经尝试了几个不同的PNG这一点。我的代码如下: <html> <head> <script type="text/javascript"> function upload(file) { // file is from a <input>

我正在尝试使用
Javascript
png
上传到。我直接使用了Imgur API中的代码,但我认为我没有正确地传递png文件,因为我收到一条错误消息,说
file.type未定义。我认为该文件是好的,因为我已经尝试了几个不同的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> 

功能上传(文件){
//文件来自标记或拖放
//文件是图像吗?
如果(!file | |!file.type.match(/image.*/)返回;
//是的!
//让我们构建一个FormData对象
var fd=新FormData();
fd.append(“image”,file);//追加文件
fd.append(“key”、“mykey”);//获取您自己的密钥:http://api.imgur.com/
//创建XHR(跨域XHR FTW!!!)
var xhr=new XMLHttpRequest();
xhr.open(“POST”http://api.imgur.com/2/upload.json);//嘘!
xhr.onload=函数(){
//大胜利!
//图像的URL为:
parse(xhr.responseText).upload.links.imgur\u页面;
}
//好的,我不处理这些错误。这是给读者的练习。
//现在,我们发送表单数据
xhr.send(fd);
}
上传到imgur

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

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


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

您使用的示例要求您使用输入元素(type=file)上载一些图像。尝试您可以使用画布访问图像数据

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

  • 使用文件创建新映像(需要位于本地域上)
  • 在加载时将图像绘制到画布
  • 使用
  • 将该数据传递给imgur

  • 谢谢你的建议。要将图像添加到画布,是图像
    id
    ?根据@skimberk1的评论,我假设我不能使用文件名引用它。无法使用文件名引用图像。您需要将其加载到img元素,然后使用drawImage将其内容加载到画布。在img的onload处理程序中执行后一部分很重要。否则就不行了。谢谢你的夸奖,这有助于我理解流程。我现在正在试验;看起来它将完成这些步骤的一部分。