Your Essential Queries
Upload A File Using jQuery and Ajax
Using PHP move_uploaded_file() function we can easily upload a file to our server
1. HTML
Create a <form> element first, which will contain a file <input>, a submit <button> and a <img> for image preview
- <div class="container">
- <form method="post" action="" enctype="multipart/form-data" id="myform">
- <div class='preview'>
- <img src="" id="img" width="100" height="100">
- </div>
- <div >
- <input type="file" id="file" name="file" />
- <input type="button" class="button" value="Upload" id="but_upload">
- </div>
- </form>
- </div>
2. CSS
Apply these styles to form element
- /* Container */.container{
- margin: 0 auto;
- border: 0px solid black;
- width: 50%;
- height: 250px;
- border-radius: 3px;
- background-color: ghostwhite;
- text-align: center;
- }
- /* Preview */.preview{
- width: 100px;
- height: 100px;
- border: 1px solid black;
- margin: 0 auto;
- background: white;
- }
- .preview img{
- display: none;
- }
- /* Button */.button{
- border: 0px;
- background-color: deepskyblue;
- color: white;
- padding: 5px 15px;
- margin-left: 10px;
- }
3. PHP
Create a php file named upload.php where you've have to validate image file first. After validating the image store the file in a server directory/folder using move_uploaded_file() function
- <?php
- if(isset($_FILES['file']['name'])){
- /* Getting file name */ $filename = $_FILES['file']['name'];
- /* Location */ $location = "upload/".$filename;
- $imageFileType = pathinfo($location,PATHINFO_EXTENSION);
- $imageFileType = strtolower($imageFileType);
- /* Valid extensions */ $valid_extensions = array("jpg","jpeg","png");
- $response = 0;
- /* Check file extension */ if(in_array(strtolower($imageFileType), $valid_extensions)) {
- /* Upload file */ if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
- $response = $location;
- }
- }
- echo $response;
- exit;
- }
- echo 0;
4. jQuery
Use these jQuery script to trigger while clicking the upload button. Validate if any file selected or not. After validating send the file using Ajax to upload.php.
- $(document).ready(function(){
- $("#but_upload").click(function(){
- var fd = new FormData();
- var files = $('#file')[0].files;
- // Check file selected or not
- if(files.length > 0 ){
- fd.append('file',files[0]);
- $.ajax({
- url: 'upload.php',
- type: 'post',
- data: fd,
- contentType: false,
- processData: false,
- success: function(response){
- if(response != 0){
- $("#img").attr("src",response);
- $(".preview img").show(); // Display image element
- }else{
- alert('file not uploaded');
- }
- },
- });
- }else{
- alert("Please select a file.");
- }
- });
- });