我有一些问题发送图像斑点数据从剪贴板到一个常规的POST形式。我在互联网上到处寻找在常规表单上这样做的方法,但是我遇到的所有解决方案中有95%使用AJAX,我想知道是否有一种方法可以在没有 AJAX的情况下实现这一。
使用下面的代码,我设法从剪贴板获取blob数据,并生成它的URL。但是,在尝试通过常规表单发送此数据时,我似乎不知道该如何操作。我尝试过以“文件”的形式发送(试图用PHP中的$_FILES
获取数据),但是它要么只发送字符串[object File]
,要么发送blob作为字符串,要么什么都不发送。
使用我遇到的一些代码,我设法用我的JavaScript到达了这里:
window.addEventListener('paste', e => {
if (document.activeElement != document.getElementById('post-text')) return; // Check active element and stop if not in text box
let blobData = e.clipboardData.items[0].getAsFile(); // Blob object
let blobUrl = e.createObjectURL(blobData); // Blob URL
document.getElementById('upload-display').src = blobUrl; // Display pasted image
document.getElementById('upload-display-container').style.display = 'block';
// Here I want to put a piece of code which adds the image data to a hidden input element, but I'm not sure how to do this.
});
如何将图像数据添加到隐藏的输入元素,当通过HTML POST表单发送时,PHP可以理解和处理它,就像发送上传的文件一样?
理想情况下,我希望将它添加到files
类型的实际<input>
中,但经过反复试验和研究,我得出结论,这是不可能的。
发布于 2019-04-18 08:56:47
感谢@ludovico为我指明了正确的方向。对于任何想知道的人来说,以下是我是如何解决这个问题的:
对于我的JavaScript (删除了页面样式函数):
window.addEventListener('paste', e => {
if (document.activeElement != document.getElementById('post-text')) return; // Check active element and stop if not in text box
let reader = new FileReader();
reader.addEventListener('load', function() {
document.getElementById('blob').value = reader.result;
}, false);
let blobData = e.clipboardData.items[0].getAsFile(); // Blob object
let blobUrl = URL.createObjectURL(blobData); // Blob URL
reader.readAsDataURL(blobData);
});
然后在PHP中,我做了一些有点奇怪的事情,但那是为了使它与我当前的代码兼容,该代码使用了常规文件上传中的$_FILES数组:
...
if (strlen($_FILES['image']['tmp_name']) == 0 && strlen($_POST['filename']) != 0) {
$temp = tmpfile();
$tempPath = tempnam(sys_get_temp_dir(), 'pastedimage');
file_put_contents($tempPath,base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $_POST['filename'])));
$fileType = getimagesize($tempPath)['mime'];
if ($fileType == false) {
// Handle error
die();
}
$_FILES['image']['name'] = 'image.'.substr($fileType, 6);
$_FILES['image']['type'] = $fileType;
$_FILES['image']['tmp_name'] = $tempPath;
$_FILES['image']['error'] = 0;
$_FILES['image']['size'] = filesize($tempPath);
}
...
https://stackoverflow.com/questions/55737380
复制相似问题