我正在尝试使用Javascript
上传png
到imgur。我直接使用Imgur API example的代码,但我不认为我正在传递png文件,因为我收到一条错误消息,说file.type is undefined
。我认为该文件是可以的,因为我已经尝试了几个不同的PNG。我的代码如下:使用javascript上传PNG到imgur
<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文件。
感谢您的建议的图像数据。为了将图像添加到画布上,是否是图像'id'?我假设我不能使用文件名来引用它,基于@ skimberk1的评论。 – djq 2012-02-12 15:53:38
使用文件名无法引用图像。您需要将其加载到img元素,然后使用drawImage将其内容加载到画布。在img的onload处理程序中完成后面的部分很重要。否则它将无法工作。 – 2012-02-12 16:09:27
感谢bebraw,这有助于我理解流程。我正在尝试http://html2canvas.hertzen.com/;它看起来会执行这些步骤的一部分。 – djq 2012-02-12 16:34:53