gpt4 book ai didi

PHP 无法读取 AJAX 发布的 BLOB FormData 文件

转载 作者:行者123 更新时间:2023-12-01 04:45:34 25 4
gpt4 key购买 nike

描述和代码:

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 函数在我的浏览器控制台中打印一个空数组:

[]

最佳答案

不使用 setTimeout,只需将 ajax 请求放在第一个成功的位置即可。当您追加 blob 时,数据不会存储在 $_POST 中,而是存储在 $_FILES 中。

    var image = $(this);
var file = $(image).attr('src');
var oReq = new XMLHttpRequest();

oReq.open('GET', file, true);
oReq.responseType = 'blob';

oReq.onload = function() {
var formData = new FormData();
formData.append('file', this.response);

$.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);
}
});
};

oReq.send();

关于PHP 无法读取 AJAX 发布的 BLOB FormData 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30345558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com