File uploading option on a website is common. But to make it work from scratch seems a very difficult task and sometimes we have to waste lots of time to figure out if things do not work properly.
In this tutorial, we will upload the file using javascript and PHP with a simple function. Javascript will be used to initiate the function and PHP to upload the file on the server. Once the setup is done, you do not need to reload the file to upload one and more images simultaneously.
HTML code to upload file
First, we need to create a file with the below code. The first input tag would be file to select the file. The second input tag would be button to initiate the javascript function.
<div > <input type="file" name="file" id="file"> <input type="button" id="btn_uploadfile" value="Upload" onclick="uploadFile()" > </div>
Javascript code to upload file
Create uploadFile()
function which will be called on the Upload button click in HTML.
// Upload file function uploadFile() { var files = document.getElementById("file").files; if(files.length > 0 ){ var formData = new FormData(); formData.append("file", files[0]); var xhttp = new XMLHttpRequest(); // Set POST method and ajax file path xhttp.open("POST", "ajaxfile.php", true); // call on request changes state xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var response = this.responseText; if(response == 1){ alert("Upload successfully."); }else{ alert("File not uploaded."); } } }; // Send request with data xhttp.send(formData); }else{ alert("Please select a file"); } }
PHP code to upload file
Make a ajaxfile.php
file and an upload
folder to store the uploaded files.
PHP will check the file extensions and only allow Pdf, Doc, Docx, Jpg, Png, Jpeg to be uploaded. If the user will try to upload other then this extension file the function will exit with response ‘0’;
<?php if(isset($_FILES['file']['name'])){ // file name $filename = $_FILES['file']['name']; // Location $location = 'upload/'.$filename; // file extension $file_extension = pathinfo($location, PATHINFO_EXTENSION); $file_extension = strtolower($file_extension); // Valid image extensions $valid_ext = array("pdf","doc","docx","jpg","png","jpeg"); $response = 0; if(in_array($file_extension,$valid_ext)){ // Upload file if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){ $response = 1; } } echo $response; exit; }