[javascript] jQuery AJAX file upload PHP

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.

This is my HTML part:

<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>

and this is my JS jquery script:

$("#upload").on("click", function() {
    var file_data = $("#sortpicture").prop("files")[0];   
    var form_data = new FormData();
    form_data.append("file", file_data);
    alert(form_data);
    $.ajax({
        url: "/uploads",
        dataType: 'script',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(){
            alert("works"); 
        }
    });
});

There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".

When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?

Can someone help my finding out whats wrong?

Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.

This question is related to javascript php jquery ajax upload

The answer is


Best File Upload Using Jquery Ajax With Materialise Click Here to Download

When you select image the image will be Converted in base 64 and you can store this in to database so it will be light weight also.


and this is the php file to receive the uplaoded files

<?
$data = array();
    //check with your logic
    if (isset($_FILES)) {
        $error = false;
        $files = array();

        $uploaddir = $target_dir;
        foreach ($_FILES as $file) {
            if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
                $files[] = $uploaddir . $file['name'];
            } else {
                $error = true;
            }
        }
        $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
    } else {
        $data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
    }

    echo json_encode($data);
?>

**1. index.php**
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid image file");
        }

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
    $test = explode('.', $_FILES['file']['name']);
    $extension = end($test);    
    $name = rand(100,999).'.'.$extension;

    $location = 'uploads/'.$name;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);

    echo '<img src="'.$location.'" height="100" width="100" />';
}

var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
    url: "upload.php",
    type: "POST",
    data : formData,
    processData: false,
    contentType: false,
    beforeSend: function() {

    },
    success: function(data){




    },
    error: function(xhr, ajaxOptions, thrownError) {
       console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
    }
});

Use pure js

_x000D_
_x000D_
async function saveFile() _x000D_
{_x000D_
    let formData = new FormData();           _x000D_
    formData.append("file", sortpicture.files[0]);_x000D_
    await fetch('/uploads', {method: "POST", body: formData});    _x000D_
    alert('works');_x000D_
}
_x000D_
<input id="sortpicture" type="file" name="sortpic" />_x000D_
<button id="upload" onclick="saveFile()">Upload</button>_x000D_
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
_x000D_
_x000D_
_x000D_

The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending

_x000D_
_x000D_
async function saveFile(inp) _x000D_
{_x000D_
    let user = { name:'john', age:34 };_x000D_
    let formData = new FormData();_x000D_
    let photo = inp.files[0];      _x000D_
         _x000D_
    formData.append("photo", photo);_x000D_
    formData.append("user", JSON.stringify(user));  _x000D_
    _x000D_
    try {_x000D_
       let r = await fetch('/upload/image', {method: "POST", body: formData}); _x000D_
       console.log('HTTP response code:',r.status); _x000D_
       alert('success');_x000D_
    } catch(e) {_x000D_
       console.log('Huston we have problem...:', e);_x000D_
    }_x000D_
    _x000D_
}
_x000D_
<input type="file" onchange="saveFile(this)" >_x000D_
<br><br>_x000D_
Before selecting the file Open chrome console > network tab to see the request details._x000D_
<br><br>_x000D_
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to upload

Upload file to SFTP using PowerShell This application has no explicit mapping for /error Schedule automatic daily upload with FileZilla jQuery AJAX file upload PHP How to find when a web page was last updated Summernote image upload on change event for file input element Multiple files upload in Codeigniter How to upload files on server folder using jsp How do I measure request and response times at once using cURL?