只需几行 JavaScript 代码。
这是一个非常简短的图片上传器,基于 imgur.com API。 如果你想做更复杂的事情(比如调整大小、裁剪、绘图、颜色等),请查看我的 上一篇博文.
背景故事:我一直在和 Imgur.com 的所有者(嗨,艾伦!)聊天。 他 最近为他的图片分享网站添加了拖放支持。 同时,艾伦还允许使用 跨域 XMLHttpRequest(谢谢!)。 因此,基本上,您可以使用他的 API 从您的 HTML 页面上传图片到他的网站,而无需任何服务器端代码 — 根本不需要。
以下是一个示例,您可以参考:
(查看完整的代码,可在 github 上获取 - 实时版本 在此)
(另外,您需要了解 FormData,请查看 此处)
function upload(file) {
// file is from a 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", "6528448c258cff474ca9701c5bab6927");
// 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);
}
就这样 :)
适用于 Chrome 和 Firefox 4(**编辑:**)以及 Safari。
关于 Paul Rouget
Paul 是一位 Firefox 开发者。
18 条评论