Using html5 to upload files using ajax and jquery

So, I'm trying to upload an image along with the form data to the server. I use the FileReader API to convert the image to data and upload to the server. I am executing code similar to an HTML5 loader using AJAX jQuery .

Data is converted to jquery, but nothing is sent to the server, and there is no error.

$('#formupload').on('submit', function(e){ e.preventDefault(); var hasError = false; var file = document.getElementById('file').files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = shipOff; function shipOff(event) { result = new Image(); result.src = event.target.result; var fileName = document.getElementById('file').files[0].name; $.post('test.php', { data: result, name: fileName }); } 

PHP code

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

Is there a problem with a large image file or FileReader API?

+4
source share
1 answer

I'm not sure if file uploading works with fileraders, but there is another way to get it working:

 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 data to a PHP file, and you can use $_FILES to process it. Unfortunately, this does not work in IE, as far as I know. There may be plugins available that make this possible in IE, but I don't know any of them.

+11
source

All Articles