| when we select a file from the browser and click submit button, the browser takes file from local machine and submit it to the server and the server does its job to save the file to the defined path. Here use ajax and jQuery to upload a file asynchronously. Used Function: FormData(): It creates a new FormData object. FormData.append(): It appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. move_uploaded_file(): It moves an uploaded file to a new location. Steps to run the Program: Create a folder upload in the xampp/htdocs directory. Copy and edit the html/jQuery code as per requirement. Create a file upload.php and copy the php code given below. Select any text or image file and click on Upload button. The file will be uploaded to the “upload” folder in xamp/htdocs. If the file is an image, it will be displayed as well, if not an image file then “Uploaded file does not have an image” message will be displayed instead. |
<script type="text/javascript">
$(document).ready(function() {
$("#but_upload").click(function() {
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file', files);
$.ajax({
url: 'upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
alert('file uploaded');
}
else{
alert('file not uploaded');
}
},
});
});
});</script>