【发布时间】:2015-08-01 10:59:14
【问题描述】:
描述和代码:
1) 我的网站中有这样的 图像文件(由动态 jQuery 上传创建):
<img src="blob:http%3A//www.example.net/6cf3e4f6-9666-41c8-a588-73f2e5057ee0">
2) 在某些操作(例如单击按钮)之后,我想将所有这些 BLOB 图像保存在服务器上。我使用 jQuery 代码:
$('button').on('click', function() {
$('#editor-label-working-area .object_container .image_container img').each(function() {
var blob = null;
var image = $(this);
var file = $(image).attr('src');
var oReq = new XMLHttpRequest();
oReq.open('GET', file, true);
oReq.responseType = 'blob';
oReq.onload = function() {
blob = new Blob([oReq.response], {
type: 'image/jpg'
});
};
oReq.send();
//(Problem No. 1) This timeOut is used just for test. I need to wait untill XMLHttpRequest is finished.
setTimeout(function() {
var formData = new FormData();
formData.append('file', blob);
$.ajax({
type: 'POST',
url: 'upload_image.php',
data: formData,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
},
error: function(response) {
console.log(response);
}
});
}, 2000);
});
});
3) 在 AJAX 请求中,我想使用我的 PHP 代码来获取发布的文件并将其保存在服务器上:
<?php
define('UPLOAD_DIR', 'labels/');
/*(Problem No. 2) Here I get empty array from $_POST method*/
$img = $_POST['file'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
问题
1.可选问题:在我的jQuery代码中,我必须使用JS超时方法等到XMLHttpRequest创建一个blob文件。这我需要了解如何使用某种等待方法,该方法以其他方式工作,而不是随机等待秒
2) 主要和最重要的问题:为什么我的 PHP 代码在 $_POST 方法中接收到空数组?如果我这样做了
echo json_encode($_POST['file']);
..,然后 AJAX .success 函数在我的浏览器控制台中打印一个空数组:
[]
【问题讨论】:
标签: php jquery ajax xmlhttprequest blob