[javascript] File Upload without Form

Without using any forms whatsoever, can I just send a file/files from <input type="file"> to 'upload.php' using POST method using jQuery. The input tag is not inside any form tag. It stands individually. So I don't want to use jQuery plugins like 'ajaxForm' or 'ajaxSubmit'.

This question is related to javascript jquery html

The answer is


Try this puglin simpleUpload, no need form

Html:

<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>

Javascript:

$('#simpleUpload').simpleUpload({
  url: 'upload.php',
  trigger: '#enviar',
  success: function(data){
    alert('Envio com sucesso');

  }
});

Step 1: Create HTML Page where to place the HTML Code.

Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.

Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajax Code url apply which one on your php file name.

JS

//$(document).on("change", "#avatar", function() {   // If you want to upload without a submit button 
$(document).on("click", "#upload", function() {
  var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
  var form_data = new FormData(); // Creating object of FormData class
  form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
  form_data.append("user_id", 123) // Adding extra parameters to form_data
  $.ajax({
    url: "/upload_avatar", // Upload Script
    dataType: 'script',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data, // Setting the data attribute of ajax with file_data
    type: 'post',
    success: function(data) {
      // Do something after Ajax completes 
    }
  });
});

HTML

<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />

Php

print_r($_FILES);
print_r($_POST);

You can use FormData to submit your data by a POST request. Here is a simple example:

var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);

$.ajax({
  url: 'upload.php',
  type: 'POST',
  processData: false, // important
  contentType: false, // important
  dataType : 'json',
  data: myFormData
});

You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).


Sorry for being that guy but AngularJS offers a simple and elegant solution.

Here is the code I use:

_x000D_
_x000D_
ngApp.controller('ngController', ['$upload',_x000D_
function($upload) {_x000D_
_x000D_
  $scope.Upload = function($files, index) {_x000D_
    for (var i = 0; i < $files.length; i++) {_x000D_
      var file = $files[i];_x000D_
      $scope.upload = $upload.upload({_x000D_
        file: file,_x000D_
        url: '/File/Upload',_x000D_
        data: {_x000D_
          id: 1 //some data you want to send along with the file,_x000D_
          name: 'ABC' //some data you want to send along with the file,_x000D_
        },_x000D_
_x000D_
      }).progress(function(evt) {_x000D_
_x000D_
      }).success(function(data, status, headers, config) {_x000D_
          alert('Upload done');_x000D_
        }_x000D_
      })_x000D_
    .error(function(message) {_x000D_
      alert('Upload failed');_x000D_
    });_x000D_
  }_x000D_
};_x000D_
}]);
_x000D_
.Hidden {_x000D_
  display: none_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div data-ng-controller="ngController">_x000D_
  <input type="button" value="Browse" onclick="$(this).next().click();" />_x000D_
  <input type="file" ng-file-select="Upload($files, 1)" class="Hidden" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

On the server side I have an MVC controller with an action the saves the files uploaded found in the Request.Files collection and returning a JsonResult.

If you use AngularJS try this out, if you don't... sorry mate :-)


Basing on this tutorial, here a very basic way to do that:

$('your_trigger_element_selector').on('click', function(){    
    var data = new FormData();
    data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
    // append other variables to data if you want: data.append('field_name_x', field_value_x);

    $.ajax({
        type: 'POST',               
        processData: false, // important
        contentType: false, // important
        data: data,
        url: your_ajax_path,
        dataType : 'json',  
        // in PHP you can call and process file in the same way as if it was submitted from a form:
        // $_FILES['input_file_name']
        success: function(jsonData){
            ...
        }
        ...
    }); 
});

Don't forget to add proper error handling


All answers here are still using the FormData API. It is like a "multipart/form-data" upload without a form. You can also upload the file directly as content inside the body of the POST request using xmlHttpRequest like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

Content-Type and Content-Disposition headers are used for explaining what we are sending (mime-type and file name).

I posted similar answer also here.


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 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 html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment