gpt4 book ai didi

javascript - XMLHttpRequest - 发送文件?

转载 作者:行者123 更新时间:2023-11-28 08:53:10 25 4
gpt4 key购买 nike

在我提交的表单中,我有:

var formData = new FormData();

for (var i = 0; i < ctx.files.length; i++) {
formData.append('file[]', ctx.files[i]);

}

在我的服务器端,我只是转储 $_POST。

我得到:

array(1) {
["file"]=>
array(1) {
[0]=>
string(17) "[object FileList]"
}
}

它以字符串形式出现,我怎样才能将它作为文件数组获取?

这是整个请求:

var formData = new FormData();

for (var i = 0; i < ctx.files.length; i++) {
formData.append('file[]', ctx.files[i]);
//formData.push(ctx.files[i]);
}

// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/site-manager-gateway/add-content');
xhr.onload = function () {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('Something went terribly wrong...');
}
};

xhr.send(formData);

最佳答案

缺少东西

发送前添加:
xhr.setRequestHeader("Content-Type","multipart/form-data");

访问文件

之后,可以像这样访问文件:

$count = count($_FILES['file']['name']);
for($i=0; $i<$count; $i++)
{
echo 'Uploaded File With FileName: '.$_FILES['file']['name'][$i].'<br/>';

}

更多信息:$_FILES 变量

http://www.php.net/manual/en/reserved.variables.files.php

如果您转到此链接,您将看到 $_FILES 变量将如下所示:

array(1) {
["upload"]=>array(5) {
["name"]=>array(3) {
[0]=>string(9)"file0.txt"
[1]=>string(9)"file1.txt"
[2]=>string(9)"file2.txt"
}
["type"]=>array(3) {
[0]=>string(10)"text/plain"
[1]=>string(10)"text/plain"
[2]=>string(10)"text/plain"
}
["tmp_name"]=>array(3) {
[0]=>string(14)"/tmp/blablabla"
[1]=>string(14)"/tmp/phpyzZxta"
[2]=>string(14)"/tmp/phpn3nopO"
}
["error"]=>array(3) {
[0]=>int(0)
[1]=>int(0)
[2]=>int(0)
}
["size"]=>array(3) {
[0]=>int(0)
[1]=>int(0)
[2]=>int(0)
}
}
}

“但是……我的文件在哪里?”

您的文件位于临时文件夹中(在 Linux 中,默认值为/tmp)。
从这个临时文件夹恢复文件的唯一方法是在每个文件上使用 php 函数:

move_uploaded_file

根据php documentation :

"This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system."

move_uploaded_file 用法

你应该这样做。如果您的上传目录名为“uploads”,则:

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$name = $_FILES["file"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>

这会将您的所有文件保存在“/uploads”目录中。

关于javascript - XMLHttpRequest - 发送文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18871106/

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