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.
Like so:
var form_data = new FormData();
formdata.append('file_name', 'some_file_name_from_form.png');
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'];
.
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.
My controller method:
public function postImage(Request $request)
{
$file = $request->get('file_name');
dd($file);
}
But when I dd
the whole request, I see this weird object:
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 } ]
Please how do I get the image sent through FormData()
object in Ajax through it's name?
Thanks for any help
You can do this.
// 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();
Check out the documentation for more information https://laravel.com/docs/5.4/requests#retrieving-uploaded-files
The api methods available on the uploaded file http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html
The code bellow is working for me:
$("#your_form").submit(function(e){
e.preventDefault();
var form = $(this);
var url = form.attr("action");
var data = new FormData(form[0]);
$.ajax({
url: url,
type: 'POST',
data: data,
cache: false,
processData: false,
contentType : false,
success: function (data) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
});
});
my problem was in property contentType. So, I set as false and it's ok!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With