我尝试创建一个类似于GMail使用的图片上传功能。您可以从桌面上复制(CTRL-C)一张图片,然后粘贴(CTRL-V)到网站上。
然后,通过XMLHttpRequest将图像上传到处理传入文件的php脚本,其中“处理”意味着对其进行重命名并存储在服务器上。
我已经能够获取图像(和数据),但是我无法成功提交和接收XMLHttpRequest。 我的Javascript代码如下:
处理 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 size”(在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字节(磁盘上为8 KB)
。
我不一定需要使用XMLHttpRequest
,这只是我首先想到的。如果有更好的方法来实现使用JavaScript实时上传图像到服务器,请告诉我们。
reader.onload = function(event) { console.log(event.target.result); // data url! submitFileForm(event.target.result, 'paste'); };
函数没有触发。 - DevZer0