Last Updated:

Uploading a file to the server using JavaScript and the jQuery library

Uploading a file to the server using JavaScript
Probably many have encountered the question "How to upload a file to the server using JS and jQuery?".

And probably not everyone was able to do it. In fact, everything is not as complicated as it seems.
In this tutorial I will describe the process of uploading a file to a server (hosting).
Ajax technology is used to exchange data between the browser and the web server.

The version of jQuery used in the recipe is 2.2.2.


 

Create primitive markup from html, head and body tags.
In the head tag, you must specify the path to the jquery library.
In the example, I'm using jquery from a google server.


In the body tag, create a form that consists of an input tag and a button.
Using input type="file" is used to select a file to be loaded.
The button tag is required to run the js code to upload the file.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    </head>
    <body>
    <body>
</html>



Set the form name="uploader", enctype="multipart/form-data", method="POST".
Form Name: name="uploader"

Form data encoding method: enctype="multipart/form-data"
Data transfer method: method="POST"


<form name="uploader" enctype="multipart/form-data" method="POST">
         Submit this file: <input name="userfile" type="file" />
         <button type="submit" name="submit">Upload</button>
</form>


All html and js markup code:


Let's go to the java script code.

To upload a file, you need to pass the entire form:


Read the form data into a variable:


Next, we use ajax technology to transfer the data to the web server.
If the file transfer is successful, a pop-up window will display a message.
If an error occurs or there is no file, a message will be displayed with the text of the problem that has occurred.


All java script code using jquery:


Now there is server-side code left to receive data from the form using the POST method of the request.

Get the root directory of the site and assign a folder for downloading files:


Read the downloaded file:


Check whether the file is downloaded.

In accordance with the incoming data, assign an accompanying message.
If the file is not downloaded, upload to the directory specified in the $uploadfile:


When performing the specified actions, a response is returned.


Source code:
<html>
     <head>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
     </head>
     <body>
     <form name="uploader" enctype="multipart/form-data" method="POST">
         Submit this file: <input name="userfile" type="file" />
         <button type="submit" name="submit">Upload</button>
     </form>
     </body>
</html>
$("form[name='uploader']").submit(function(e) {
var formData = new FormData($(this)[0]);
$.ajax({
             url: 'file.php',
             type: "POST",
             data:formData,
             async: false
             success: function (msg) {
                 alert(msg);
             },
             error: function(msg) {
                 alert('Error!');
             },
             cache: false
             contentType: false
             processData: false
         });
    <script type="text/javascript">
     $("form[name='uploader']").submit(function(e) {
         var formData = new FormData($(this)[0]);

         $.ajax({
             url: 'file.php',
             type: "POST",
             data:formData,
             async: false
             success: function (msg) {
                 alert(msg);
             },
             error: function(msg) {
                 alert('Error!');
             },
             cache: false
             contentType: false
             processData: false
         });
         e.preventDefault();
     });
     </script>
$uploaddir = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR;
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
     $out = "The file is valid and was uploaded successfully.\n";
} else {
     $out = "Possible file upload attack!\n";
}

<?php

$uploaddir = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR;
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
     $out = "The file is valid and was uploaded successfully.\n";
} else {
     $out = "Possible file upload attack!\n";
}

echo $out;

?>

<html>
     <head>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
     </head>
     <body>
     <form name="uploader" enctype="multipart/form-data" method="POST">
         Submit this file: <input name="userfile" type="file" />
         <button type="submit" name="submit">Upload</button>
     </form>
     <script type="text/javascript">
     $("form[name='uploader']").submit(function(e) {
         var formData = new FormData($(this)[0]);

         $.ajax({
             url: 'file.php',
             type: "POST",
             data:formData,
             async: false
             success: function (msg) {
                 alert(msg);
             },
             error: function(msg) {
                 alert('Error!');
             },
             cache: false
             contentType: false
             processData: false
         });
         e.preventDefault();
     });
     </script>
     </body>
</html>