使用javascript将png上传到imgur [英] Uploading a png to imgur using javascript

查看:118
本文介绍了使用javascript将png上传到imgur的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Javascript png 上传到imgur 。我直接使用了Imgur API 示例中的代码,但我认为我没有正确传递png文件收到错误消息,说 file.type未定义。我认为该文件没问题,因为我尝试了几个不同的png。我的代码如下:

I'm trying to use Javascript to upload a png to imgur. I've used the code directly from the Imgur API example, but I don't think I am passing the png file properly as I get an error message saying file.type is undefined. I think the file is ok as I've tried this with a few different pngs. My code is as follows:

<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文件相同的目录中。

The png file test.png is stored in the same directory as my html file.

推荐答案

你的例子正在使用期望您使用输入元素(type = file)上传一些图像。尝试此示例。您可以使用Canvas 这样来访问图像数据。

The example you are using expects that you use input element (type=file) to upload some image. Try this example. You can access image data using a Canvas like this.

总结一下,你需要这样做:

To summarize, you'll need to do this:


  1. 用你的文件创建新图像(需要在本地域上)

  2. 在onload处将图像绘制到Canvas

  3. 使用此方法

  4. 将该数据传递给imgur 喜欢这里

  1. Create new Image with your file (needs to be on local domain)
  2. Draw the image to a Canvas at onload
  3. Extract image data using this method
  4. Pass that data to imgur like here

这篇关于使用javascript将png上传到imgur的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆