使用 javascript 将 png 上传到 imgur

2024-04-09

我正在尝试使用Javascript上传一个png to imgur http://imgur.com/。我直接使用了 Imgur API 中的代码example http://api.imgur.com/examples,但我认为我没有正确传递 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> 

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


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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 javascript 将 png 上传到 imgur 的相关文章