JQuery File Upload

JQuery file upload is very easy and it gives rich user experience.  Here I show you how we can upload a file through ajax and jquery.

You need the latest jquery file. you can download it. here we are including jquery from googleapis.com server but we recommend that you should download all files in your website folder.

In this JQuery file upload example we have created a input field with type of file and then we are calling a function onChangeHandler on onChange event of this input file field.

This function stores selected file in global variable data which is a object of class FormData.
FormData in a javascript class that is used to upload files.

Then we created a button and called a function saveFile on the click event of this function.
This function is uploading file to server using jquery ajax request.

In this ajax request we have added two more options that is:


contentType: false,
processData: false,

That is required in file upload.


<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>
<script>
const data = new FormData()
function saveFile() {

$.ajax({
type:"POST",
data:data,
contentType: false,
processData: false,
url: 'uploadfile.php',
success:function(response) {
$("#results").html(response);
}
});
}
function onChangeHandler(event) {
data.append('filename', event.target.files[0]);
}
</script>
</head>
<body>
<div>
<label>Upload Image</label>
<input type="file" name="my_image" id="my_image" onChange="onChangeHandler(event)"/>
</div>
<div>
<input type="button" value="Upload" name="upload_file" onClick="saveFile(this);" />
</div>
<div id="results">
</div>

</body>
</html>

below is the php code to handle server side request. You can take this example for learning purpose. But you can change it according to you requirment.


<?php

if($_FILES) {

$allowedExts = array("gif", "jpeg", "jpg", "png");

$temp = explode(".", $_FILES["file"]["name"]);

$extension = end($temp);

$results = array();

$results[] = "Upload: " . $_FILES["file"]["name"];

$results[] = "Type: " . $_FILES["file"]["type"];

$results[] = "Size: " . ($_FILES["file"]["size"] / 1024) . " kB";

$results[] = "Temp file: " . $_FILES["file"]["tmp_name"];

$filename = $_FILES["file"]["name"];

move_uploaded_file($_FILES["file"]["tmp_name"], $filename);

$results[] = "Stored in: " . "upload/" . $_FILES["file"]["name"];

}

print json_encode($results);

This is a working example of JQuery File Upload. you can create these two files and run it at you localhost server.

Leave a Reply

Your email address will not be published. Required fields are marked *

5 × three =