如何在Laravel中读取FormData对象 [英] how to read FormData object in Laravel
问题描述
我正在尝试将表单提交给Laravel 5控制器方法.我了解在php中,您可以定义一个FormData对象,将输入字段附加到该对象,然后将其发送到服务器,在服务器中您现在可以使用输入字段名称提取值.
I am trying to ajax submit form to a Laravel 5 controller method. I understand that in php, you can define a FormData object, append the input fields to the object and send it to the server where you can now extract the values using the input field names.
像这样:
var form_data = new FormData();
formdata.append('file_name', 'some_file_name_from_form.png');
在ajax调用中将form_data
作为data
发送时,我可以使用$_FILES['file_name']['name'];
在PHP中获取文件.
When form_data
is sent as the data
in the ajax call, I can get the file in PHP by using the $_FILES['file_name']['name'];
.
因此,我在Laravel控制器方法中尝试了相同的逻辑.我只是尝试在$request
对象中获取文件名,但只得到null.
So I tried this same logic in a Laravel controller method. I tried just to grab the name of the file in the $request
object but only got null.
我的控制器方法:
public function postImage(Request $request)
{
$file = $request->get('file_name');
dd($file);
}
但是当我dd
整个请求时,我看到了这个奇怪的对象:
But when I dd
the whole request, I see this weird object:
array:1 [ "file_name" => UploadedFile {#199 -测试:错误 -originalName:"work-fitness_00255959.png" -mimeType:图片/png" -大小:34215 -错误:0 #hashName:null 路径:"/tmp" 档名:"phpVodsUg" 基本名称:"phpVodsUg" 路径名:"/tmp/phpVodsUg" 扩大: "" realPath:"/tmp/phpVodsUg" 时间:2017-06-04 12:42:26 mTime:2017-06-04 12:42:26 cTime:2017-06-04 12:42:26 索引节点:17573243 大小:34215 烫发:0100600 拥有人:1000 组:1000 类型:文件" 可写:true 可读性:true 可执行文件:false 文件:true 目录:假 链接:错误 } ]
array:1 [ "file_name" => UploadedFile {#199 -test: false -originalName: "work-fitness_00255959.png" -mimeType: "image/png" -size: 34215 -error: 0 #hashName: null path: "/tmp" filename: "phpVodsUg" basename: "phpVodsUg" pathname: "/tmp/phpVodsUg" extension: "" realPath: "/tmp/phpVodsUg" aTime: 2017-06-04 12:42:26 mTime: 2017-06-04 12:42:26 cTime: 2017-06-04 12:42:26 inode: 17573243 size: 34215 perms: 0100600 owner: 1000 group: 1000 type: "file" writable: true readable: true executable: false file: true dir: false link: false } ]
请问如何通过图像的名称通过Ajax中的FormData()
对象发送图像?
Please how do I get the image sent through FormData()
object in Ajax through it's name?
感谢您的帮助
推荐答案
您可以执行此操作.
// get the `UploadedFile` object
$file = $request->file('file_name');
$file = $request->file_name;
// get the original file name
$filename = $request->file('file_name')->getClientOriginalName();
$filename = $request->file_name->getClientOriginalName();
查看文档以获取更多信息 https://laravel.com/docs /5.4/requests#retrieving-uploaded-files
Check out the documentation for more information https://laravel.com/docs/5.4/requests#retrieving-uploaded-files
上载文件 http://上可用的api方法api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html
这篇关于如何在Laravel中读取FormData对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!