【问题标题】:Uploading a png to imgur using javascript使用 javascript 将 png 上传到 imgur
【发布时间】:2012-03-04 05:07:49
【问题描述】:

我正在尝试使用Javascriptpng 上传到imgur。我直接使用了来自 Imgur API example 的代码,但我认为我没有正确传递 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> 

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

【问题讨论】:

    标签: javascript png imgur


    【解决方案1】:

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

    总而言之,您需要这样做:

    1. 使用您的文件创建新图像(需要在本地域中)
    2. 在加载时将图像绘制到画布上
    3. 使用this method提取图像数据
    4. 将该数据传递给 imgur like here

    【讨论】:

    • 感谢您的建议。为画布添加图像,是图像id?根据@skimberk1 的评论,我认为我无法使用文件名来引用它。
    • 无法使用文件名引用图像。您需要将其加载到 img 元素,然后使用 drawImage 将其内容加载到画布。在 img 的 onload 处理程序中执行后一部分很重要。否则将无法正常工作。
    • 感谢 bebraw,这有助于我理解流程。我目前正在尝试html2canvas.hertzen.com;看起来它会执行这些步骤的一部分。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2010-12-21
      • 2016-07-17
      • 2014-05-09
      相关资源
      最近更新 更多