我尝试制作一种类似于 GMail 使用的图像上传功能。您从桌面复制 (CTRL-C) 图像并将其粘贴 (CTRL-V) 到网站上。然后通过 XMLHttpRequest 将图像上传到处理传入文件的 php 脚本,其中“处理”意味着重命名并存储在服务器上。
我已经可以获取图像(和数据),但我无法成功提交和接收 XMLHttpRequest。我的 Javascript 代码如下所示:
document.onpaste = function(e){
var items = e.clipboardData.items;
console.log(JSON.stringify(items));
if (e.clipboardData.items[1].kind === 'file') {
// get the blob
var imageFile = items[1].getAsFile();
console.log(imageFile);
var reader = new FileReader();
reader.onload = function(event) {
console.log(event.target.result); // data url!
submitFileForm(event.target.result, 'paste');
};
}
};
function submitFileForm(file, type) {
var formData = new FormData();
formData.append('file', file);
formData.append('submission-type', type);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'php/image-upload.php');
xhr.onload = function () {
if (xhr.status == 200) {
console.log('all done: ');
} else {
console.log('Nope');
}
};
xhr.send(formData);
}
处理 php( php/image-upload.php
) 看起来像这样:
$base64string = $_POST['file'];
file_put_contents('img.png', base64_decode($base64string));
我认为$_POST['file']
保持空置,但我不确定。更重要的是,我还遇到“blob 大小”(使用 console.log() 显示)比实际图像大小大得多。但也许这无关紧要或由编码引起。
开发者控制台显示了这一点。
{"0":{"type":"text/plain","kind":"string"},"1":{"type":"image/png","kind":"file"},"length":2} image-upload.js:8
Blob {type: "image/png", size: 135619, slice: function}
如果我通过右键单击实际图像文件来查看文件信息,它会显示5,320 bytes (8 KB on disk)
大小。
我不一定需要使用 a XMLHttpRequest
,这只是我首先想到的。如果有更好的方法可以使用 javascript 实现将图像实时上传到服务器,请告诉我们。