繁体   English   中英

具体5 - 如何在php中通过ajax获取文件

[英]concrete5 - how to get files uploaded through ajax in php

我正在尝试通过 ajax 上传多个文件,但我不知道如何在 PHP 中获取上传的文件。 我送他们

var attachments = $('.attachment-file');
var post_data = new FormData();
if (attachments.length > 0) {
    attachments.each(function(i, v) {
        post_data.append('my_file', $(v)[0].files);
    });
}
$.ajax({
    cache: false,
    contentType: false,
    processData: false,
    method: 'post',
    type: 'post',
    data: post_data,
    url: form.attr('action'),
})
.done(function(response) {
...

但是当我尝试像这样在 PHP 中获取文件时:

$data = $this->request->request->all();
$files = $data['my_file']; \Log::Info(var_dump_safe($files));
foreach ($files as $file) {

它抱怨“为 foreach() 提供的参数无效”。 转储显示字符串(17)“[object FileList]”。 如果文件在那里,我如何获取它?

文件的 JS 日志 console.log($(v)[0].files); 看起来像这样:

FileList(1)
0: File
lastModified: 1604656019000
name: "Screenshot_20201106_204451.png"
size: 66866
type: "image/png"
webkitRelativePath: ""
<prototype>: FilePrototype { name: Getter, lastModified: Getter, webkitRelativePath: Getter, … }
length: 1
<prototype>: FileListPrototype { item: item(), length: Getter, … }

\\Log::Info(var_dump_safe($data)); 的整个表单数据转储; 看起来像这样:

array(4) {
["topic"]=>
string(2) "24"
["title"]=>
string(5) "Title"
["content"]=>
string(4) "Test"
["my_file"]=>
string(8) "Array(1)"
}

和 \\Log::Info(var_dump_safe($data['my_file'])); 数组的转储:

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

我如何获取文件数据?

工作解决方案:

这是使用 ajax 发送多个文件的方法。

JS:

var post_data = new FormData();
attachments.each(function(i, v) {
    post_data.append('my_file[]', v.files[0]);
    console.log(v.files[0]);
});

PHP:

$files = $this->request->files;
$files = $files->get('my_file');
foreach ($files as $file) {
    \Log::Info(var_dump_safe($file->getClientOriginalName()));
}

现在一切正常。

附注。 不要忘记不要发布和上传大于 post_max_size 和 upload_max_size 的 PHP 限制的文件!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM