Using Html5 File Uploads With Ajax and Jquery

Using HTML5 file uploads with AJAX and jQuery

It's not too hard. Firstly, take a look at FileReader Interface.

So, when the form is submitted, catch the submission process and

var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...


function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
$.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}

Then, on the server side (i.e. myscript.php):

$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);

Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.

Check out fwrite() and jQuery.post().

On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).

using html5 for file upload with ajax and jquery

I'm not sure if file upload works with filereaders, but there is a different way to make it work:

var formData = new FormData($(".file_upload_form")[0]);
$.ajax({
url: "upload_file.php", // server script to process data (POST !!!)
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // check if upload property exists
// for handling the progress of the upload
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
success: function(result) {
console.log($.ajaxSettings.xhr().upload);
alert(result);
},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: "application/octet-stream", // Helps recognize data as bytes
processData: false
});

function progressHandlingFunction(e) {
if (e.lengthComputable) {
$("#progress").text(e.loaded + " / " + e.total);
}
}

This way you send the data to the PHP file and you can use $_FILES to process it. Unfortunately, this does not work in IE as far as I know. There might be plugins available that make this possible in IE, but I don't know any of them.

Ajax File Upload (HTML5)

With jquery.form plugin, it's very simple to do what you want:

HTML:

<form id="form" action="upload_page.php" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="file">
<input type="submit" value="Upload file">
</form>

<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>

JS:

$(document).ready(function () {

var options = {
beforeSend: function () {
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function (event, position, total, percentComplete) {
$("#bar").width(percentComplete + '%');
$("#percent").html(percentComplete + '%');

},
success: function () {
$("#bar").width('100%');
$("#percent").html('100%');

},
complete: function (response) {
$("#message").html("<font color='green'>" + response.responseText + "</font>");
},
error: function () {
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");

}

};

$("#form").ajaxForm(options);

});

This will also give you a nice progress bar which you can style however you want.

Plugin page

jQuery Ajax File Upload

File upload is not possible through AJAX.

You can upload file, without refreshing page by using IFrame.

You can check further details here.


UPDATE

With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers.

FormData support starts from following desktop browsers versions.

  • IE 10+
  • Firefox 4.0+
  • Chrome 7+
  • Safari 5+
  • Opera 12+

For more detail, see MDN link.

Html 5 upload file , ajax , jquery

This line is wrong:

data: {file:file},

it should be:

data: file,

Also, you need to give a name to the file input, it should be:

<input type="file" name="file" id="fileInputUpload">

File upload using HTML5 along with ajax not working for ajax loaded form

Where do you set that handler, before the form is loaded? In that case try this

$(':file').live('change', function(){
...
}

jQuery AJAX file upload PHP

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.

Your HTML is fine, but update your JS jQuery script to look like this:

(Look for comments after // <-- )

$('#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: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:

<?php

if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}

?>

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(

// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],

// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

HTML5 + jQuery AJAX upload - No file sent to server

For some reason the problem was with the formData variable, previously defined as such:

var formData = new FormData($('.form-uploadXLS')[0]);

I've changed the index to 1 like this..

var formData = new FormData($('.form-uploadXLS')[1]);

.. and for some reason it works now.



Related Topics



Leave a reply



Submit