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.
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.
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'); } }) })
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.
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.
Finally, when we submit this form we got the file. Here I have used dd() helper method for debugging.
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…