concrete5-如何在php中通过ajax上传文件 [英] concrete5 - how to get files uploaded through ajax in php

查看:69
本文介绍了concrete5-如何在php中通过ajax上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to upload multiple files through ajax but I can't figure out how to get the uploaded files in PHP. I sent them

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文件时:

but when I try to get the files in PHP like so:

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

它抱怨为foreach()提供了无效的参数".转储显示字符串(17)"[对象文件列表]".如果文件在那里,我如何获取它?

it complains "Invalid argument supplied for foreach()". The dump shows a string(17) "[object FileList]". If the file is in there, how do I get it?

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

JS log for the files console.log($(v)[0].files); looks like this:

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))的整个表单数据转储;看起来像这样:

The whole form data dump of \Log::Info(var_dump_safe($data)); looks like this:

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']));;

and the dump of the array of \Log::Info(var_dump_safe($data['my_file']));:

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

如何获取文件数据?

推荐答案

有效的解决方案:

这是使用ajax发送多个文件的方式.

Here's how you send multiple files with 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()));
}

现在一切正常.

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

PS. Don't forget not to post and upload files bigger than the PHP limits of post_max_size and upload_max_size!

这篇关于concrete5-如何在php中通过ajax上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆