Send File using JQuery AJAX and FormData

Thanks for reading my blog I hope that my code can be useful for someone in somewhere.

I am going to give you a simple example of how to send a file using JQuery’s AJAX with FormData.

If you do not know what is FormData, you can find all his methods in the next link and is you want more examples visit Using Form Data Objects.

Let’s create the HTML for our example.


<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<title>Send File With FormData</title>
<link rel=”stylesheet” href=”css/bootstrap.min.css”>
</head>
<body>
<div class=”container”>
<div class=”row”>
<div class=”form-group”>
<div class=”col-sm-12">
<div class=”input-group”>
<label for=”txtFirstName”>
First Name:
<input type=”text” class=”form-control” name=”txtFirstName” value=”” placeholder=”Name”>
</label>
</div>
</div>
<div class=”col-sm-12">
<div class=”input-group”>
<label for=”txtLastName”>
Last Name:
<input type=”text” class=”form-control” name=”txtLastName” value=”” placeholder=”Last Name”>
</label>
</div>
</div>
<div class=”col-sm-12">
<div class=”input-group”>
<input type=”file” name=”myPicture” >
</div>
</div>
<div class=”col-sm-12">
<button type=”button” data-action=”save” class=”btn btn-primary”>Save</button>
</div>
</div>
</div>
</div>
<script type=”text/javascript” src=”js/jquery.min.js”></script>
<script type=”text/javascript” src=”js/main.js”></script>
</body>
</html>

As you can see we are not using the Form tag. We are using a Div tag and inside of this div we create the inputs and the button to send the Data. If you want to use a ‘Form’ tag you can do it just remember to use preventDefault() to prevent the normal behavior of the form and of course change the type of the button to submit.

Ok I created a script tag for jQuery and another for management our ajax request to the server.

Let’s put the next code in our main.js file.

var jq = $(document);
sendFile = function sendFile () {
return {
sendInformation: function sendInformation (firstName, lastName, picture) {
// >> Create the FormData
var myFormData = new FormData();
myformData.append('firstName', firstName);
myformData.append('lastName', lastName);
myformData.append('picture', picture);
   $.ajax({
url: '/path/to/file',
type: 'POST',
data: myFormData
dataType: false,
contentType: false
});
}
};
};
var mySendFile = sendFile();
jq.find(“button[data-accion=’save’]”).on(“click”, function (){
mySendFile.sendInformation( $(‘input[name=”txtFirstName”]’).val()
, $(‘input[name=”txtLastName”]’).val()
, $(‘input[type=”file”]’)[0].files[0]);
});

In this javascript file I’m using Functional Programing.

Ok I going to explain the code, FormData is a Javascript Object for that reason we can create an instance and use it as you can see in the code. The Append method is to add to our object a new item, keep in mind FormData works as a JSON Array, this meaning using ‘key’ — ‘value’ to storage a new item.

As note, use the same name of the variable (key in the FormData Object) in your server side.
Continue with the code, now I will explain why I put ‘dataType’ and ‘contentType‘ equals to false in the AJAX request.

This is because content type by default is “application/x-www-form-urlencoded; charset=UTF-8”.

Data type by default JQuery will try to recognize the type of our variables into “(xml, json, script, or html)” if our type does not match JQuery throw an error, for this reason we put to false the content type because we do not want to JQuery check our variables.

If you want to know more about JQuery AJAX visit JQuery — Ajax.

Note: Remember use the HttpPostedFile in your server function to receive the file that you send from AJAX.

Example using our code and C# in the next function. 
Public string myFunction (string firstName, string lastName, HttpPostedFile picture) {
Try {
// Your code
} catch (Exception e) {return e.message;}
};

And this was the example of how to send files with JQuery AJAX using FormData.

Thanks for reading me :)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.