Upload file object with jquery ajax to Laravel?
Sometimes we want to upload a javascript file object with jquery ajax to Laravel. As we know, it is easy to submit an html form to backend (Laravel) via ajax. But when we talk about file objects, it seems difficult to do, if we are not completely aware about the ajax usage.
Today, we are going to discuss how we can upload javascript file objects to Laravel.
Create a file input
First thing, we need an html input with type file to get the file object. We might get this file object from any way like from an html form, jquery editor plugins etc.
Then we need to write a jquery ajax request to upload this file object to laravel or any backend technology.
While writing ajax requests keep a few things in mind.
Javascript FormData API to upload file object with jquery ajax
Js FormData API helps us to upload the form data to the server. Today it will also help us to upload our file object.
let form = $('#SaveFile'); let path = `${APP_URL}/save-file`; form.on('submit', function(e) { e.preventDefault(); let file = $(this).find(':file')[0].files[0]; let formD = new FormData(); formD.append('avc', file); $.ajax({ method: 'POST', url: path, data: formD, processData : false, contentType : false, success: function(re) { console.log('success', re); }, error: function() { console.log('error'); } }) })
ProcessData
The processData by default is true and processData means to transform the html form data into a query string. For example: http://example.com?name=abc&email=acb@gmail.com
This string query is good fit for content type “application/x-www-form-urlencoded”
To send the file with ajax request, we need to set processData false.
ContentType
The contentType can be false or a string that describes the type of content sent to the server via ajax request. If the content type is set to false, it means no data is sent to the server.
The default content type is “application/x-www-form-urlencoded”, others are multipart/form-data, text/plain, application/json etc.For sending the file object to the server, we need to set contentType false.
Final Result
Finally, when we submit this form we got the file. Here I have used dd() helper method for debugging.