Okay so I have an uploader script that I customized and it works great. I have 2 more steps that I need to do for it to be complete and it is beyond my scope and I have read and tried numerous things and still am not getting the results that I want.
Again only code that is releative to my issue will be posted as the code works perfect and does not need any changing with the exception of trying to get a value from AJAX to PHP.
FULL JS FILE BELOW:
jQuery(document).ready(function () {
var img_zone = document.getElementById('img-zone'),
collect = {
filereader: typeof FileReader != 'undefined',
zone: 'draggable' in document.createElement('span'),
formdata: !!window.FormData
},
acceptedTypes = {
'image/png': true,
'image/jpeg': true,
'image/jpg': true,
'image/gif': true
};
// Function to show messages
function ajax_msg(status, msg) {
var the_msg = '<div class="alert alert-'+ (status ? 'success' : 'danger') +'">';
the_msg += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>';
the_msg += msg;
the_msg += '</div>';
$(the_msg).insertBefore(img_zone);
}
// Function to upload image through AJAX
function ajax_upload(files) {
$('.progress').removeClass('hidden');
$('.progress-bar').css({ "width": "0%" });
$('.progress-bar span').html('0% complete');
var productTestID = "333746240";
var formData = new FormData(this);
formData.append('productTestID',productTestID);
//formData.append('any_var', 'any value');
for (var i = 0; i < files.length; i++) {
//formData.append('img_file_' + i, files[i]);
formData.append('img_file[]', files[i]);
}
$.ajax({
url : "upload.php", // Change name according to your php script to handle uploading on server
type : 'post',
data : formData,
dataType : 'json',
processData: false,
contentType: false,
error : function(request){
ajax_msg(false, 'An error has occured while uploading photo.');
},
success : function(json){
var img_preview = $('#img-preview');
var col = '.col-sm-2';
$('.progress').addClass('hidden');
var photos = $('<div class="photos"></div>');
$(photos).html(json.img);
var lt = $(col, photos).length;
$('col', photos).hide();
$(img_preview).prepend(photos.html());
$(col + ':lt('+lt+')', img_preview).fadeIn(2000);
if(json.error != '')
ajax_msg(false, json.error);
},
progress: function(e) {
if(e.lengthComputable) {
var pct = (e.loaded / e.total) * 100;
$('.progress-bar').css({ "width": pct + "%" });
$('.progress-bar span').html(pct + '% complete');
}
else {
console.warn('Content Length not reported!');
}
}
});
}
// Call AJAX upload function on drag and drop event
function dragHandle(element) {
element.ondragover = function () { return false; };
element.ondragend = function () { return false; };
element.ondrop = function (e) {
e.preventDefault();
ajax_upload(e.dataTransfer.files);
}
}
if (collect.zone) {
dragHandle(img_zone);
}
else {
alert("Drag & Drop isn't supported, use Open File Browser to upload photos.");
}
// Call AJAX upload function on image selection using file browser button
$(document).on('change', '.btn-file :file', function() {
ajax_upload(this.files);
});
// File upload progress event listener
(function($, window, undefined) {
var hasOnProgress = ("onprogress" in $.ajaxSettings.xhr());
if (!hasOnProgress) {
return;
}
var oldXHR = $.ajaxSettings.xhr;
$.ajaxSettings.xhr = function() {
var xhr = oldXHR();
if(xhr instanceof window.XMLHttpRequest) {
xhr.addEventListener('progress', this.progress, false);
}
if(xhr.upload) {
xhr.upload.addEventListener('progress', this.progress, false);
}
return xhr;
};
})(jQuery, window);
});
So the above code is from the .js file. The script uploads multiple selected files, which works fine. From what I have read, in order to get additional values sent to PHP you have to use the .append(), which is what I have done below. I created the var productTestID and gave it a value and then added it to the formData using the append().
My issue is how do I read it in PHP?
I have tried $_POST[productTestID] and get no results at all. I even tried doing an isset() and it comes back not set.
So what do I need to do in my PHP code to read or extract that value? Below is an excerpt from my upload.php file and like I said the file uploads work and this is how they are being accessed.
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$error = '';
$img = '';
$dir = dirname($_SERVER['SCRIPT_FILENAME'])."/". DIR_WS_IMAGES . "upload/";
$extensions = array("jpeg","jpg","png");
foreach($_FILES['img_file']['tmp_name'] as $key => $tmp_name )
Further down in my upload.php file:
//MOVE TO FINAL LOCATION
$uploaded_file = $dir.$file_name;
if (rename($uploaded_file, $uniqueFileName))
{
$productTestID = $_POST['productTestID'];
}
$img .= '<div class="col-sm-2"><div class="thumbnail">';
$img .= '<img src="'.$dir.$file_name.'" />'.$uploaded_file . '<br>' .$fileName.'<br>'.$uniqueFileName.'<br>This Product Id is:';
$img .= $productTestID;
$img .= '</div></div>';
}
Thank You,
Shawn Mulligan
Related
I am making a cart system using PHP and AJAX. Everything works pretty fine, except for the updating part. When the user clicks outside of the number form, the subtotal will update automatically. I used AJAX for this, but doesn't work. I tested this with the search, everything was fine.
AJAX function:
function initXML() { //Adaptation for old browsers
var _xmlhttp;
if (window.XMLHttpRequest) {
_xmlhttp = new XMLHttpRequest();
} else {
_xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return _xmlhttp;
}
function ajaxFormValidate(_config) {
/*Structure
type: 'GET' or 'POST',
url: 'request URL' Default: location.href,
method: true or false (optional). False for non-async, true for async,
sendItem: file or data to be sent,
success: a callback function when the request is complete
error: a fallback function when the request is failed
*/
if (!_config.type) {
_config.type = 'POST'; //Automatically set type to POST if no type property is declared
}
if (!_config.url) {
_config.url = location.href; //Automatically set url to self if no url property is declared
}
if (!_config.method) {
_config.method = true; //Automatically set method to true if no method property is declared
}
var _xmlHttp = initXML(); //Declare request variable
_xmlHttp.onreadystatechange = function(){
if (_xmlHttp.readyState === 4 && _xmlHttp.status === 200) {
if (_config.success) {
_config.success(_xmlHttp.responseText);
}
}
else {
if (_config.error) {
_config.error(_xmlHttp.responseText);
}
}
}; //Check readyState and status to handle the request properly
//Handle the items sent
var _Itemstring = [], _sendItem = _config.sendItem;
if (typeof _sendItem === "string") {
var _arrTmp = String.prototype.split.call(_sendItem, '&');
for (var i = 0; i < _arrTmp.length; i ++) {
var _tmpData = _arrTmp[i].split('=');
_Itemstring.push(encodeURIComponent(_tmpData[0]) + "=" + encodeURIComponent(_tmpData[1]));
}
}
else if (typeof _sendItem === "object" && !(_sendItem instanceof String || (FormData && _sendItem instanceof FormData))) {
for (var k in _sendItem) {
var _tmpData = _sendItem[k];
if (Object.prototype.toString.call(_tmpData) === "[object Array]") {
for (var j = 0; j < _tmpData.length; j ++) {
_Itemstring.push(encodeURIComponent(k) + '[]=' + encodeURIComponent(_tmpData[j]));
}
}
else {
_Itemstring.push(encodeURIComponent(k) + '=' + encodeURIComponent(_tmpData));
}
}
}
_Itemstring = _Itemstring.join('&');
if (_config.type === 'GET') {
_xmlHttp.open('GET', _config.url + "?" + _Itemstring, _config.method);
_xmlHttp.send();
}
else if (_config.type === 'POST') {
_xmlHttp.open('POST', _config.url, _config.method);
_xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
_xmlHttp.send(_Itemstring);
}
}
AJAX called inside a JS file handling the changes in the inputs
// JavaScript Document
window.addEventListener('load', function(){
var _ranum = document.getElementsByClassName('ranum');
for (var i = 0; i < _ranum.length; i ++) {
_ranum[i].addEventListener('blur', function(){ //Check click outside
var _this = this;
ajaxFormValidate({
type:'POST',
sendItem: {
u: _this.value, //Send the value after the change
id: _this.id, //Send the product id
},
success: function(response){
console.log('SUCCESS');
}
});
}, false);
}
}, false);
Handling the changes in PHP file
var_dump($_POST['u']);
if (isset($_POST['id'], $_POST['u'])) {
if (!empty($_POST['id']) && !empty($_POST['u'])) {
$id = mysqli_real_escape_string($conn, $_POST['id']);
$u = mysqli_real_escape_string($conn, $_POST['u']);
if (isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id] = $u;
}
}
}
I see the it logged out 'SUCCESS' in the console, however, when I use var_dump($_POST['u']) it doesn't work. Also, it updates the subtotal only if I reload the page.
What did I do wrong? I pretty sure my AJAX function is correct, and JS logged out 'SUCCESS', so what's the problem? Thanks very much
I am using laravel framework 5.2. I have successfully implemented dropzone and i have also done with upload images. Now problem is that when i want to delete the image from folder it gives me error. I think my code is not right for deleting image.
Here is my add Upload image Function i have uploaded images in session:-
public function addContributorimages(Request $request){
if($request->ajax()){
$image=$_FILES['file'];
if(!empty($image)){
if($image['error']==0){
$name = pathinfo($_FILES['file']['name']);
$ext = $name['extension'];
$rand=str_random(24).'.'.$ext;
$destination = base_path() . '/public/images/ContributorImages/';
if(is_uploaded_file($image['tmp_name'])){
list( $width, $height, $source_type ) = getimagesize($image['tmp_name']);
if ($width >= 10 && $height >= 10){
move_uploaded_file($image['tmp_name'],$destination.$rand);
$request->session()->put('contributorimage.'.str_random(5).'.image',$rand);
$images = $request->session()->get('contributorimage');
echo "<pre>"; print_r($images);
}
else{
echo "Error";die;
}
}
}
}
}
}
This is my add Function of images
Here is my dropzone code :-
Dropzone.autoDiscover = false;
var fileList = new Array;
var i =0;
$("#my-awesome-dropzone").dropzone({
method:'POST',
maxFiles: 10,
paramName: "file",
maxFilesize: 10,
addRemoveLinks: true,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
clickable: true,
init: function() {
// Hack: Add the dropzone class to the element
$(this.element).addClass("dropzone");
this.on("sending",function(file, xhr, formData) {
formData.append("_token", "{{ csrf_token() }}");
});
this.on("success", function(file, serverFileName) {
fileList[i] = {"serverFileName" : serverFileName, "fileName" : file.name,"fileId" : i };
//console.log(fileList);
i++;
});
this.on("removedfile", function(file) {
var rmvFile = "";
for(f=0;f<fileList.length;f++){
if(fileList[f].fileName == file.name)
{
rmvFile = fileList[f].serverFileName;
if (rmvFile){
$.ajax({
type: 'POST',
url: '../contributor/delete-subimages/'+rmvFile,
});
}
}
}
});
},
url: '../contributor/add-subimages',
});
});
My images are successfully uploaded but i want to remove the image from session as well as from folder can anyone help me how to do that
Here is my delete function of image:-
public function deleteContributorImage(Request $request,$name = null){
$imageName=explode('.',$name);
$imageRandomName = $request->session()->get('contributorimage.'.$imageName[0].'.image');
$destination = base_path() . '/public/images/ContributorImages/';
if(unlink($destination.$imageRandomName)){
$request->session()->forget('contributorimage.'.$imageName[0]);
echo "success";
}
else{
echo "failed";
}
}
Now when i upload images it create this sesssion now i am having two images in session
Array
(
[Dkf08] => Array
(
[image] => whywu3dprVPKKkhUgdIMAdLQ.jpg
)
[rH5NV] => Array
(
[image] => i2sZEqjMdiQHcKRyy5Km9vlu.jpg
)
)
can anyone hlep me how to slove this issue . Thanks in advance :)
you have to create one hidden filed for that and when you remove file from dropzone than that file name should be save in that hidden filed.
myDropzone.on('removedfile', function (file) {
var hidden_filed= document.getElementById('hidden_filed').value;
if (alreadyRemove == "") {
$('#deleteImage').val(file.name);
} else {
$('#deleteImage').val(hidden_filed+ ',' + file.name);
}
});
after that get that field as POST data in controller. From file name you can delete Image as usual.
I'm using laravel 4.2 and currently I don't how to save a csv file into public\csv\ directory using AJAX. I'm still finding some answers. Maybe someone can help me with this.
Here's my code:
In blade view:
{{Form::open(['route' => 'file_upload', 'files' => true, 'id' => 'upload_form', 'method' => 'POST'])}}
{{Form::file('csv_upload', ['id' => 'uploaded_file', 'accept' => 'text/csv'])}}
{{Form::submit('submit', ['class' => 'btn btn-primary btn-xs', 'id' => 'upload'])}}
{{Form::close()}}
Javascript Ajax:
var ajax_ready = 1
var token = {{Session::get('_token')}}
if($.type(originalOptions.data) === 'string') {
options.data = originalOptions.data+"&_token="+token;
}else if($.type(originalOptions.data) === 'object') {
//Here I got a new error
}else{
options.data = $.param(($.extend(originalOptions.data, {'_token':mmad_token})));
}
options.url = originalOptions.url.slice(0,originalOptions.url.indexOf("?_token="));
if (ajax_ready!=1){
jqXHR.abort();
}
ajax_ready = 0;
});
$('form#upload_form').on('submit', function(e){
e.preventDefault();
var uploadFile = $('#uploaded_file');
var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
var file = $('input[name="csv_upload"]').val();
if($.inArray(ext, ["csv"]) === -1) {
alert("Please upload a .csv file!");
return false;
}
var csv = uploadFile[0].files;
var form = new FormData(this);
var csvFile = {lastModifed: csv[0].lastModified, fileName: csv[0].name, size: csv[0].size, fileType: csv[0].type};
$.post('{{ URL::route("file_upload") }}?_token={{Session::token()}}',{
data: form
}).done(function(response){
});
});
PHP:
public function upload_csv()
{
$inputs = Input::all();
$csvFile = $inputs['data']['fileName'];
$path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
$path2 = public_path('csv/');
if(is_dir($path2))
{
#move_uploaded_file($csvFile, $path2.$csvFile); //This line can't move the uploaded files in my desired directory
}
return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);
}
This code below does work when not using AJAX:
if(Input::hasFile('csv_upload'))
{
$file = Input::file('csv_upload');
$originalFilename = $file->getClientOriginalName();
$rules = ['csv_upload' => 'required|file:csv'];
$validate = Validator::make(['csv_upload' => $file], $rules);
if($validate->fails())
{
return json_encode(['error' => 1, 'description' => 'File must be in .csv format']);
}
$path = public_path('/csv/');
if(!file_exists($path))
{
mkdir($path);
}
}
Console.log of csv
You can not move file because when you submit form with ajax file is not being sent with ajax,For sending file you have to send file with FormData() javascript Object.
If you check in upload_csv controller by putting print_r($_FILES); you will get empty array.
So use FormData on client side for appending file, then try agian.
You aren't getting error beacuse you have used php Error Control Operators likes#move_uploaded_file($csvFile, $path2.$csvFile);.
if you need working example then tell me i will give it to you.
Code For Your Help:
1. In blade view:
<script type="text/javascript">
$('form#upload_form').on('submit', function(e){
e.preventDefault();
var uploadFile = $('#uploaded_file');
var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
var file = $('input[name="mmad_csv_upload"]').val();
if($.inArray(ext, ["csv"]) === -1) {
alert("Please upload a .csv file!");
return false;
}
var csv = uploadFile[0].files;
var formData = new FormData($(this)[0]);
formData.append('uploaded_file', $("#uploaded_file")[0].files[0]);
formData.append('lastModifed', csv[0].lastModified);
formData.append('fileName', csv[0].name);
console.log(formData);
$.ajax({
url: '{{ URL::route("file_upload") }}',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function (returndata) { //alert(returndata); return false;
}
});
});
</script>
2.Controller
public function file_upload(Request $request)
{
$inputs = Input::all();
$csvFile = $inputs['fileName'];
$path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
$path2 = public_path('/csv/');
if(is_dir($path2))
{
$success = $request->file('uploaded_file')->move($path2, $csvFile);
}
return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);
}
To move the uploaded file to a new location, you should use the move method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a more permanent destination of your choosing:
Input::file('fileName')->move($destinationPath, $fileName);
If you need additional validations, you can check it at http://laravel.com/docs/5.1/requests#files
Default AJAX POST does not support file uploads. Use jQuery Form to upload files successfully. Full documentation of file upload at http://malsup.com/jquery/form/#file-upload
Below my example of a recentlty build script... My Controller uploads the files to S3, but is easy to be implemented with local storage.
var progress = function(event, position, total, percent) {
$(".progress-bar").width(percent + '%');
$(".progress-bar").html(percent + '%');
if(percent > 50) {
$(".progress-bar").css('color','#fff');
}
if(percent == 100) {
setTimeout(function(){
$(".progress").html('<span class="processing-msg">Processing... Please be patient!</span>');
$(".processing-msg").fadeIn('slow');
}, 1000);
}
}
var success = function(data) {
var obj = $.parseJSON(data);
$("#"+obj.hidden, parent.document).val(obj.filename);
var src = 'https://s3.amazonaws.com/spincms'+obj.path+'thumb_'+obj.filename;
$("#uploaded-"+obj.hidden, parent.document).html('<img class="img-circle uploaded-img" src="' + src + '">');
$(".progress").html('<span class="processing-msg-next">File has been uploaded and processed. Do not forget to submit the form!</span>');
}
var options = {
target: '#output',
uploadProgress: progress,
success: success,
resetForm: true
};
$(document).on('click', "#upload-now", function(e) {
$(".progress").html('<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>');
if($("#upload-form input[type=file]")[0].files.length == 0) {
$(".progress").html('<span class="processing-msg-next">No file selected!</span>');
return false;
} else {
var name = $("#upload-form input[name='name']").val();
var token = $("#upload-form input[name='_token']").val();
var file_name = $("#upload-form input[type=file]")[0].files[0].name;
$("#upload-form").ajaxSubmit(options);
}
}
});
Since you are using jQuery you can use the form plugin as it will make things much more easier for you to work with for example , this is the jquery part that you will use :
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#upload_form').ajaxForm(function() {
alert("Your file has been uploaded, thanks");
});
});
and in your controller you can code it like :
pubilc function postUpload()
{
$success = false;
if(Request::ajax())
{
if(Input::hasFile('csv_upload'))
{
$file = Input::file('csv_upload');
if(!File::isDirectory(storage_path('csv'))) {
File::createDirectory(storage_path('csv'));
}
$file->move(storage_path('csv'), $file->getClientOriginalName());
// now your file is on app/storage/csv folder
$filePath = storage_path('csv/'.$file->getClientOriginalName());
$success = true;
}
}
return Response::json(['success'=>$success]);
}
Good day,
I am trying to create a script that loads my Browser Geolocation and following sends it to a file that saves it.
The problem is. The data does not get send.
And an even bigger problem is that I have tried many things but I am quite clueless.
I added several alerts but the alerts do not show up.
What should the script do?
Run once every five seconds and requesting your GeoLocation.
When you click accept on your phone and accept for all from this source you will have an active GPS alike tracking.
The code :
<script type="text/javascript">
function success(position) {
///SaveActiveGeoLocation();
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success, error);
}
else{
error('not supported');
}
function SaveGeoLocation(){
var Lat = position.coords.latitude;
var Lon = position.coords.longitude;
var Accuracy = position.coords.accuracy;
///######## SENDING THE INFORMATION BY AJAX
$.ajax({
type : "POST", /// **** SEND TYPE
url : "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA
data : {
'Lat' : Lat,
'Lon' : Lon,
'GeoAccuracy' : Accuracy
},
///######## IN CASE OF SUCCESS
success:function(response){
if( response == "ok" ){
alert('SEND!');
}
else{
alert( "Response = " + response );
}
}
}
);
}
$(document).ready(function() {
$.ajaxSetup({
cache: false
}); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
///alert('HOI!');
SaveGeoLocation();
}, 5000);
// the "10000" here refers to the time to refresh the div. it is in milliseconds.
/// **** DEFAULT LOADING
///SaveGeoLocation();
});
</script>
The file that saves the send POST data :
<?php
include('function.geolocation.class.php');
$geo = new GeoLocation();
$Lat = $_POST['Lat'];
$Lon = $_POST['Lon'];
$GeoAccuracy = $_POST['GeoAccuracy'];
$IP = $geo->GetIP();
$file = 'location.txt';
$address = $geo->getAddress($Lat, $Lon);
$contents = $Lat.'|'.$Lon.'|'.$IP.'|'.$GeoAccuracy.'|'.date('Y-m-d H:i:s').'|'.$address.PHP_EOL;
$handle = fopen($file, 'a');
fwrite($handle, $contents);
fclose($handle);
echo 'ok';
?>
One problem I can see is the variable position does not exists in the context of the SaveGeoLocation method
function success(position) {
//SaveActiveGeoLocation();
window.position = position;
}
function SaveGeoLocation() {
if (!window.position) {
return;
}
//your stuff
}
There is no need to call SaveGeoLocation using interval, you can call SaveGeoLocation from the success callback like
function success(position) {
SaveActiveGeoLocation(position);
}
function SaveGeoLocation(position) {
//your stuff
}
If you want to save the location continuously
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
function saveLocation() {
navigator.geolocation.getCurrentPosition(success, error);
}
function success(position) {
var Lat = position.coords.latitude;
var Lon = position.coords.longitude;
var Accuracy = position.coords.accuracy;
///######## SENDING THE INFORMATION BY AJAX
$.ajax({
type: "POST", /// **** SEND TYPE
url: "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA
data: {
'Lat': Lat,
'Lon': Lon,
'GeoAccuracy': Accuracy
},
///######## IN CASE OF SUCCESS
success: function (response) {}
}).done(function (response) {
if (response == "ok") {
alert('SEND!');
} else {
alert("Response = " + response);
}
}).always(function () {
setTimeout(saveLocation, 5000)
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
}
if (navigator.geolocation) {
saveLocation();
} else {
error('not supported');
}
});
Admittedly, there are similar questions lying around on Stack Overflow, but it seems none quite meet my requirements.
Here is what I'm looking to do:
Upload an entire form of data, one piece of which is a single file
Work with Codeigniter's file upload library
Up until here, all is well. The data gets in my database as I need it. But I'd also like to submit my form via an AJAX post:
Using the native HTML5 File API, not flash or an iframe solution
Preferably interfacing with the low-level .ajax() jQuery method
I think I could imagine how to do this by auto-uploading the file when the field's value changes using pure javascript, but I'd rather do it all in one fell swoop on for submit in jQuery. I'm thinking it's not possible to do via query strings as I need to pass the entire file object, but I'm a little lost on what to do at this point.
Can this be achieved?
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).
With jQuery (and without FormData API) you can use something like this:
function readFile(file){
var loader = new FileReader();
var def = $.Deferred(), promise = def.promise();
//--- provide classic deferred interface
loader.onload = function (e) { def.resolve(e.target.result); };
loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
loader.onerror = loader.onabort = function (e) { def.reject(e); };
promise.abort = function () { return loader.abort.apply(loader, arguments); };
loader.readAsBinaryString(file);
return promise;
}
function upload(url, data){
var def = $.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = $.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });
promise.abort = function(){ return req.abort.apply(req, arguments); }
return promise;
}
var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}
for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}
return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};
//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, $file[0].files[0].name];
upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});
With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})