Working with HTML5's File API, the upload is made via an object called upload in the XMLHttpRequest. This is the tutorial I'm working with (and the Google cache mirror since it's down at the moment). This is the relevant part:
// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();
// Update progress bar
xhr.upload.addEventListener("progress", function (evt) {
As you can see, to track the upload progress, the XMLHttpRequest object has a property named upload, which we can add an event handler.
My question is: has jQuery an equivalent?. I'm attempting to leave the code as clean as and cross-browser compatible as possible, for whenever Microsoft thinks it's a good idea (although it sounds like it will be in 2012 or 2013).
Here is what I came up with to get around the issue. The $.ajax() call allows to provide a callback to generate the XHR. I just generate one before calling the request, set it up and then create a closure to return it when $.ajax() will need it. It would have been much easier if they just gave access to it through jqxhr, but they don't.
var reader = new FileReader();
reader.onloadend = function (e) {
var xhr, provider;
xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (e) {
// ...
}, false);
}
provider = function () {
return xhr;
};
// Leave only the actual base64 component of the 'URL'
// Sending as binary ends up mangling the data somehow
// base64_decode() on the PHP side will return the valid file.
var data = e.target.result;
data = data.substr(data.indexOf('base64') + 7);
$.ajax({
type: 'POST',
url: 'http://example.com/upload.php',
xhr: provider,
dataType: 'json',
success: function (data) {
// ...
},
error: function () {
// ...
},
data: {
name: file.name,
size: file.size,
type: file.type,
data: data,
}
});
};
reader.readAsDataURL(file);
The documentation for the jqXHR (the superset of the XMLHttpRequest that is returned from jQuery's .ajax() call) does not describe the update feature as being exposed, which does not mean it isn't exposed. This question, though, seems to indicate that upload is not exposed. The answer provides a way to get to the native XMLHttpRequest object.
In versions before jQuery 1.5 the XMLHttpRequest object was exposed directly, and so you can access any feature of it that the browser supports. This tutorial for building a drag and drop uploader does just that.
A search for jquery html 5 file upload brings up this plugin to do multiple file upload using the HTML 5 file API, but this plugin does not currently work in IE. If you don't want to use HTML 5 and instead do want to have support cross-browser now, there are other plugins you can look into for jQuery on the jQuery plugin site.
Related
I'm trying to integrate Chen Fengyuan's 'cropperjs' into a website I'm designing and I have the interface working fine with the crop box doing as it should. However, my limited knowledge of Javascript and jQuery has brought me to a standstill.
What I would like to do is click on a button under the canvas (similar to the Get Cropped Canvas button) and have the cropped image posted to the server using a simple jQuery AJAX call.
I don’t need a preview of the cropped image as the image is already previewed on the interface. However, I can't seem to do this successfully because every time I try and use the methods provided in the 'cropperjs' documentation, I get a browser errors like:
ReferenceError: cropper is not defined
I've tried various methods and have seen a lot of solutions online but I just can't seem to get it right. I know I'm doing something very wrong but because I don't understand Javascript and jQuery well enough. I'm really struggling. The documentation mentions initialising with the Cropper constructor but I don't know how to do this and I'm guessing this is where my problem is? Can anyone help?
I've manage to painfully solve this myself so for anyone who's interested, here's the code I used:-
var $image = $("#image");
var cropper = $image.cropper();
var baseURL = window.location.protocol+'//'+window.location.host;
var pho_id = $("input[name=pho_id]").val();
var mem_id = $("input[name=mem_id]").val();
var photopath = $("input[name=photopath]").val();
$image.cropper('getCroppedCanvas').toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
formData.append('pho_id', pho_id);
formData.append('mem_id', mem_id);
formData.append('photopath', photopath);
$.ajax(baseURL+'/path/', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
}, 'image/jpeg', 0.8);
After reading around for a couple of hours I'm not sure the best way to approach it. I've got a list of restful resource urls (same domain) selected by the user, and I'd like to package those for immediate download. Any pointers to a 'correct' method would be great :)
I'm using Django Rest Framework and have tried using JSZip.js on the front end, but just get garbage - the zip file wont open (I assume I'm doing something wrong with the type somewhere...)
$(document).ready(function () {
$.ajax({
type: "GET",
url:"http://127.0.0.1:8000/data/test/?format=fits",
contentType: "application/fits",
accepts: "application/fits",
})
.done(function(data) {
console.log("Success");
var zip = new JSZip();
// create a file
zip.file(data, 'nameoffile.fits');
var content = null;
if (JSZip.support.uint8array){
content = zip.generate({type:"uint8array"});
} else {
content = zip.generate({type:"string"});
};
$('#download').click(function(){
var blob = zip.generate({type:"blob"});
saveAs(blob, "downloadable.zip");
});
})
.fail(function(data) {
console.log("Failed");
})
.always(function() {
console.log("In Always");
});
});
I see two issues:
it's zip.file('nameoffile.fits', data), not zip.file(data, 'nameoffile.fits')
$.get only handles text content but FITS files look like binary files
$.get tries to decode the content from its encoding (usually UTF-8). With a binary file, the decoding step corrupts the content. You can check this step by converting the content to a blob and using saveAs to download it.
To fix that, see this page: either use JSZipUtils, an XMLHttpRequest with responseType = 'arraybuffer', or any ajax framework that let you download binary content.
I have an angularjs project which retrieves JSON files from a server and uses the contents to display the data in the screen.
I'm using a service to load the data, and this service calls the server for a new JSON file every 2 seconds (I removed that from the code below for simplicity).
var data = $resource(:file.json', {}, {
query: {method: 'GET', params: {file: '#file'}}
});
this.load = function(file, myFunction) {
data.query({file:file}, function(data) {
myFunction(data);
}
}
Now, these files can be really big and sometimes there's no need to process the file because there are no changes from the previous one received. I have a property in the JSON file with the version number, and I should not process the file unless that version number is higher than the one in the previous file.
I can do that by calling the query service, which loads the file contents into a js object and then check the version, if the file is really big it might take a while to load it. Is there a way to access that property value (version) ONLY and then, depending on it, load the file into a js object?
EDIT: The thing that I'm guessing is that loading a 1MB JSON file to check a version number inside it might take a while (or maybe no and that $resource action is really fast, anyone knows?), but I'm not really sure that it can be done any other way, as I'm checking a specific property inside the file.
Many thanks in advance.
HTML5 and Javascript now provides a File API which can be used to read the file line by line. You can find information regarding this feature here:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
This will slice the full file into string and take just the first line(asuming the version is in there)
data.substr(0, data.indexOf("\n"));
--
Bonus:
Also in this answer you will find out how to read the first line of a file:
https://stackoverflow.com/a/12227851/2552259
var XHR = new XMLHttpRequest();
XHR.open("GET", "http://hunpony.hu/today/changelog-en.txt", true);
XHR.send();
XHR.onload = function (){
console.log( XHR.responseText.slice(0, XHR.responseText.indexOf("\n")) );
};
Another question with the same topic:
https://stackoverflow.com/a/6861246/2552259
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://website.com/file.txt", true);
txtFile.onreadystatechange = function()
{
if (txtFile.readyState === 4) { // document is ready to parse.
if (txtFile.status === 200) { // file is found
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n");
}
}
}
txtFile.send(null);
Do you have access to the json files?
I'm not sure how you generate your json files but you could try adding the version number in the filename and check if a newer filename exists. I have not tested this but maybe it's worth a try.
There are a lot of questions about file upload with Android but most of them without answer and actually none of them are related with javascript or php.
I'm seeing strange behaviour when selecting a file to upload on Android (4.4.4) native browser (HTC One_M8) and what it gives me is this;
C:\fakepath\image:12045
"Fakepath" part doesnt bother me, what bothers me is that I cant get file name out of /input type="file"/ html tag.
I'm sending files with $.ajax and it works on Chrome, FF, Safari (desktop & iPhone), It works also on my M8 with Chrome, but not with native browser.
This is what I use to get selected files;
var filedata = document.getElementById("userFile");
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
// showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("userFile[]", file);
}
}
And this is how I send them to handle.php
$.ajax({
url: 'handle.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
}
return myXhr;
},
data: formdata,
dataType:'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function(xhr, opt) {
$('#control-console').append($('input[type=file]').val());
$('input[type=file]').val("");
},
success: function() {
},
complete: function(podatki) {
$('#control-console').append(podatki.responseJSON.name);
console.log(podatki)
$.each(podatki.responseJSON.name, function(i, val) {
console.log(val);
insertFrame(val);
});
processing = false;
}
});
I haven't found any documentation about this so I don't really know if this is a bug in Android native browser or do I have to use different approach.
Has anyone faced the same problem and maybe found a solution ?
I have researched a lot and i have made a solution for android only. When you are in browser and iPhone, you can use your solution as it is working perfectly. But, android have a security issue. So, i had to make a solution for android.
You can follow my solution here.
What I have researched in last few hours is when file being uploaded is within the gallery for the android phone, due to security checks above problem happens. No file name, extension, size will be readable.
To workaround this:
1- Click on browse button, you will be taken to gallery of your device.
2- On right corner of gallery click Options image ("...") and Enable "Internal Storage".
3- Make sure the file you upload is in Internal Storage.
4- Access "Internal Storage" option while uploading.
5- File should show the correct name.
I'm using file api and xhr2 spec. I created an uploader (backed by flash for older browsers) that was using FormData and $.ajax(options) where the FormData object with File was part of options.data object. Everything was working.
Now I decided to remove FormData because of weak browser support. And I can't figure a way to upload the file other than
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(file);
Which doesn't return Promise that I can use in the recursion function.
My code is like this :
startUpload: function() {
var that = this;
that.recurseSend(that.queue);
},
_initProgressListener: function (options, file) {
var that = this;
var xhr = $.ajaxSettings.xhr();
options.contentType = 'multipart/form-data';
options.processData = false;
options.type = 'POST';
// WHAT TO DO HERE TO avoid FormData???? What ever I put into options.data - fails
/* THIS WOULD WORK
var formData = new FormData();
formData.append('file', file);
options.data = formData;
*/
if (xhr.upload && xhr.upload.addEventListener) {
xhr.upload.addEventListener('progress', function (e) {
that._onProgress(e, file);
}, false);
options.xhr = function () {
return xhr;
};
}
},
recurseSend: function (queue) {
var file = queue.pop();
if(file != undefined) {
var that = this;
var options = that.options;
that._initProgressListener(options, file);
var send = function() {
jqXHR = ($.ajax(options)).done(function(result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, file);
queue.stats['successful_uploads']++;
}).fail(function(jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, file);
queue.stats['upload_errors']++;
}).always(function(result, textStatus, jqXHR) {
that._onAlways(result, textStatus, jqXHR, file);
queue.stats['files_queued']--;
that.recurseSend(queue);
});
return jqXHR;
};
this._beforeSend(file);
return send();
}
},
To make it short, $.ajax(options) resolves into xhr.send(formData) if options.data = FormData but how do I make it resolve into xhr.send(file) ?
EDITED: I was playing with it and if I set options.data = file; then $.ajax(options) executes xhr.send(theFile); but with error Error: INVALID_STATE_ERR: DOM Exception 11
and the request is sent as POST multipart/form-data request, but without the multipart body with file in it
And if I put it into options.data = {file: file}; it is serialized no matter if processData property is set to true or not.
You can manually generate the MIME data for the upload from the HTML5 file data read using FileReader or similar APIs. Check out: https://github.com/coolaj86/html5-formdata . This will do more or less that, although it depends on getAsBinary() -- changing it to also be able to use FileReader and readAsBinaryString() would probably be more cross-browser-compatible.
Note that this still won't work at all in IE7/8, and as others have said, there is no way to do it without resorting to Flash or iframes. That being said, if you're using File, presumably you don't care about IE7 or IE8 anyway...
Whenever you are dealing with uploading arbitrary data from a users machine, the answer is usually "no, and if you can, that's a bug".
This strikes me as something that would fall under the umbrella of security violations. You can't change the value of the file input control or do many other things to it including read the true path of the file or its contents. Furthermore, on some platforms you don't have even the file size (IE, I'm looking at you) without some security dialog popping up (via an activex control). Given all of these problems I would probably be tempted to say that even if you did find a solution, it would be potentially viewed as a bug in the future and removed or changed.
In other words, I don't think it's a safe thing to do unless you find a reputable source explicitly supporting it ... like the chromium dev blog.
I my self have used valums ajax uploader. You can get it from here:
http://valums.com/ajax-upload/. It works pretty nicely. I don't know the exact implementation details, but here's a very short description:
"This plugin uses XHR for uploading multiple files with progress-bar in FF3.6+, Safari4+, Chrome and falls back to hidden iframe based upload in other browsers, providing good user experience everywhere."
So it sounds like its very close to what you want. Here's another bit of info describing the way it works from the servers point of view (from server/readme.txt):
For IE6-8, Opera, older versions of other browsers you get the file as
you normally do with regular form-base uploads.
For browsers which upload file with progress bar, you will need to get the raw
post data and write it to the file.
So it requires special handling on the server side. Luckily it comes with several reference server side implementations (perl, php and java) so that shouldn't be too much of hassle. Happy ajax uploading :)
How can I upload files asynchronously?
It seems you can't do this without going through an iFrame. There seem to be working snippets in the answer i linked, and several plugins that do it for you.
* edit since I am getting comments on it *
Yes it is possible- http://caniuse.com/xhr2 - theres no IE support below 10 though..
Heres a tutorial:
http://www.html5rocks.com/en/tutorials/file/xhr2/
http://www.profilepicture.co.uk/ajax-file-upload-xmlhttprequest-level-2/