FormData() append method (browser compatibility problems) - javascript

Server-side dev here who's a JS newbie (1 week old). This question is about browser compatibility issues (mobile browsers especially).
I'm trying to use pure JS/Ajax to process image uploads via a web form. Specifically, at one point I'm using the append method on FormData() with filename.
Here's the code:
function overwrite_default_submit(e) {
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("image", img_to_send, img_name);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.open('POST', e.target.action);
xhr.send(form_data);
}
According to https://developer.mozilla.org/en-US/docs/Web/API/FormData/append, browser compatibility for append in mobiles is not universal. Two problems cited are:
XHR in Android 4.0 sends empty content for FormData with blob.
And
Prior to Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4),
if you specified a Blob as the data to append to the object, the
filename reported in the "Content-Disposition" HTTP header was an
empty string; this resulted in errors being reported by some servers.
Starting in Gecko 7.0 the filename "blob" is sent.
My questions are:
1) What alternative can I use to fix these specific situations?
2) What checks can I put in place to elegantly fall back (e.g. to a non-JS solution - which I've already implemented) in case there's just no way through?
Would love to see illustrative examples of how the experts do it.
In case warranted, here's my full code:
// converting image data uri to a blob object
function dataURItoBlob(dataURI,mime_type) {
var byteString = atob(dataURI.split(',')[1]);//supported
var ab = new ArrayBuffer(byteString.length);//supported
var ia = new Uint8Array(ab);//supported
for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); }//supported
return new Blob([ab], { type: mime_type });
}
The above is called in the following:
var canvas = document.createElement('canvas');
canvas.width = img_width;
canvas.height = img_height;
var ctx = canvas.getContext("2d");
ctx.drawImage(source_img, 0, 0, img_width, img_height);
return dataURItoBlob(canvas.toDataURL(mime_type,quality/100),mime_type);
And ultimately, the returned blob is appended to a FormData() object and sent via Ajax:
function overwrite_default_submit(e) {
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("image", img_blob, img_name);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(form_data);
}

Related

How do I Convert URL to Blob with javascript or jquery [duplicate]

I'd like to build a simple HTML page that includes JavaScript to perform a form POST with image data that is embedded in the HTML vs a file off disk.
I've looked at this post which would work with regular form data but I'm stumped on the image data.
JavaScript post request like a form submit
** UPDATE ** Feb. 2014 **
New and improved version available as a jQuery plugin:
https://github.com/CoeJoder/jquery.image.blob
Usage:
$('img').imageBlob().ajax('/upload', {
complete: function(jqXHR, textStatus) { console.log(textStatus); }
});
Requirements
the canvas element (HTML 5)
FormData
XMLHttpRequest.send(:FormData)
Blob constructor
Uint8Array
atob(), escape()
Thus the browser requirements are:
Chrome: 20+
Firefox: 13+
Internet Explorer: 10+
Opera: 12.5+
Safari: 6+
Note: The images must be of the same-origin as your JavaScript, or else the browser security policy will prevent calls to canvas.toDataURL() (for more details, see this SO question: Why does canvas.toDataURL() throw a security exception?). A proxy server can be used to circumvent this limitation via response header injection, as described in the answers to that post.
Here is a jsfiddle of the below code. It should throw an error message, because it's not submitting to a real URL ('/some/url'). Use firebug or a similar tool to inspect the request data and verify that the image is serialized as form data (click "Run" after the page loads):
Example Markup
<img id="someImage" src="../img/logo.png"/>
The JavaScript
(function() {
// access the raw image data
var img = document.getElementById('someImage');
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
var dataUrl = canvas.toDataURL('image/png');
var blob = dataUriToBlob(dataUrl);
// submit as a multipart form, along with any other data
var form = new FormData();
var xhr = new XMLHttpRequest();
xhr.open('POST', '/some/url', true); // plug-in desired URL
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert('Success: ' + xhr.responseText);
} else {
alert('Error submitting image: ' + xhr.status);
}
}
};
form.append('param1', 'value1');
form.append('param2', 'value2');
form.append('theFile', blob);
xhr.send(form);
function dataUriToBlob(dataURI) {
// serialize the base64/URLEncoded data
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(dataURI.split(',')[1]);
}
else {
byteString = unescape(dataURI.split(',')[1]);
}
// parse the mime type
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// construct a Blob of the image data
var array = [];
for(var i = 0; i < byteString.length; i++) {
array.push(byteString.charCodeAt(i));
}
return new Blob(
[new Uint8Array(array)],
{type: mimeString}
);
}
})();
References
SO: 'Convert DataURI to File and append to FormData
Assuming that you are talking about embedded image data like http://en.wikipedia.org/wiki/Data_URI_scheme#HTML
****If my assumption is incorrect, please ignore this answer.**
You can send it as JSON using XMLHttpRequest.
Here is sample code: (you may want to remove the header part ('data:image/png;base64,') before sending)
Image
<img id="myimg" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
Button
<input id="subbtn" type="button" value="sub" onclick="sendImg()"></input>
Script
function sendImg() {
var dt = document.getElementById("myimg").src;
var xhr = new XMLHttpRequest();
xhr.open("POST", '/Home/Index', true); //put your URL instead of '/Home/Index'
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { //4 means request finished and response is ready
alert(xhr.responseText);
}
};
var contentType = "application/json";
xhr.setRequestHeader("Content-Type", contentType);
for (var header in this.headers) {
xhr.setRequestHeader(header, headers[header]);
}
// here's our data variable that we talked about earlier
var data = JSON.stringify({ src: dt });
// finally send the request as binary data
xhr.send(data);
}
EDIT
As #JoeCoder suggests, instead of json, you can also use a FormData object and send in Binary format. Check his answer for more details.

XMLHttpRequest to upload a file with parameters

I want to upload a file using XMLHTTRequest for Safari 5.1 and pass parameters in the POST request.How can this be achieved?It should be in plain javascript without using any API and I am doing this as Safari does not support FileReader in 5.1 version.
var fd = new FormData();
fd.append('file', $files[i]);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function(){alert("Done!");}, false);
xhr.open("POST", url.getUrl('myurl'));
xhr.send(fd);
Is the above piece of code correct?How do I pass parameters to the POST request.
The code looks good.
If you want to pass additional parameters to the POST you will have to add them to the FormData.
var fd = new FormData();
// here the POST parameters
fd.append('parameter1', 'XXXX' );
fd.append('parameter2', 'YYYY' );
// The rest of your code
fd.append('file', $files[i]);
...
EDIT: I am not sure however if this functionality is supported in Safari 5.1
Try if( window.FormData === undefined ) or if( window.FormData !== undefined ).
for more reference click here
You should also try this one!
<script>
var client = new XMLHttpRequest();
function upload()
{
var file = document.getElementById("uploadfile");
/* Create a FormData instance */
var fd = new FormData();
/* Add the file */
fd.append("upload", file.files[0]);
client.open("post",url.getUrl('myurl'), true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
}
/* Check the response status */
client.onreadystatechange = function()
{
if (client.readyState == 4 && client.status == 200)
{
alert(client.statusText);
}
}
</script>
As FormData, the ability to send() one, and the upload property (and its onprogress event) are all part of XMLHttpRequest level 2, you can test for .upload to see if you've got a level 2. I don't have a Mac handy, but the function (sadly, but correctly) returns false for Opera 11.50 (and true for Firefox 4).

How can I upload an embedded image with JavaScript?

I'd like to build a simple HTML page that includes JavaScript to perform a form POST with image data that is embedded in the HTML vs a file off disk.
I've looked at this post which would work with regular form data but I'm stumped on the image data.
JavaScript post request like a form submit
** UPDATE ** Feb. 2014 **
New and improved version available as a jQuery plugin:
https://github.com/CoeJoder/jquery.image.blob
Usage:
$('img').imageBlob().ajax('/upload', {
complete: function(jqXHR, textStatus) { console.log(textStatus); }
});
Requirements
the canvas element (HTML 5)
FormData
XMLHttpRequest.send(:FormData)
Blob constructor
Uint8Array
atob(), escape()
Thus the browser requirements are:
Chrome: 20+
Firefox: 13+
Internet Explorer: 10+
Opera: 12.5+
Safari: 6+
Note: The images must be of the same-origin as your JavaScript, or else the browser security policy will prevent calls to canvas.toDataURL() (for more details, see this SO question: Why does canvas.toDataURL() throw a security exception?). A proxy server can be used to circumvent this limitation via response header injection, as described in the answers to that post.
Here is a jsfiddle of the below code. It should throw an error message, because it's not submitting to a real URL ('/some/url'). Use firebug or a similar tool to inspect the request data and verify that the image is serialized as form data (click "Run" after the page loads):
Example Markup
<img id="someImage" src="../img/logo.png"/>
The JavaScript
(function() {
// access the raw image data
var img = document.getElementById('someImage');
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
var dataUrl = canvas.toDataURL('image/png');
var blob = dataUriToBlob(dataUrl);
// submit as a multipart form, along with any other data
var form = new FormData();
var xhr = new XMLHttpRequest();
xhr.open('POST', '/some/url', true); // plug-in desired URL
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert('Success: ' + xhr.responseText);
} else {
alert('Error submitting image: ' + xhr.status);
}
}
};
form.append('param1', 'value1');
form.append('param2', 'value2');
form.append('theFile', blob);
xhr.send(form);
function dataUriToBlob(dataURI) {
// serialize the base64/URLEncoded data
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(dataURI.split(',')[1]);
}
else {
byteString = unescape(dataURI.split(',')[1]);
}
// parse the mime type
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// construct a Blob of the image data
var array = [];
for(var i = 0; i < byteString.length; i++) {
array.push(byteString.charCodeAt(i));
}
return new Blob(
[new Uint8Array(array)],
{type: mimeString}
);
}
})();
References
SO: 'Convert DataURI to File and append to FormData
Assuming that you are talking about embedded image data like http://en.wikipedia.org/wiki/Data_URI_scheme#HTML
****If my assumption is incorrect, please ignore this answer.**
You can send it as JSON using XMLHttpRequest.
Here is sample code: (you may want to remove the header part ('data:image/png;base64,') before sending)
Image
<img id="myimg" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
Button
<input id="subbtn" type="button" value="sub" onclick="sendImg()"></input>
Script
function sendImg() {
var dt = document.getElementById("myimg").src;
var xhr = new XMLHttpRequest();
xhr.open("POST", '/Home/Index', true); //put your URL instead of '/Home/Index'
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { //4 means request finished and response is ready
alert(xhr.responseText);
}
};
var contentType = "application/json";
xhr.setRequestHeader("Content-Type", contentType);
for (var header in this.headers) {
xhr.setRequestHeader(header, headers[header]);
}
// here's our data variable that we talked about earlier
var data = JSON.stringify({ src: dt });
// finally send the request as binary data
xhr.send(data);
}
EDIT
As #JoeCoder suggests, instead of json, you can also use a FormData object and send in Binary format. Check his answer for more details.

How to upload/POST multiple canvas elements

I have to create an image uploader for a future project (No flash, IE10+, FF7+ etc.) that does image resizing/converting/cropping on the clientside and not on the server.
So I made a javascript interface where the user can 'upload' their files and get resized/cropped in the browser directly, without ever contacting the server. The performance is OK, not that good, but it works.
The endresult is an array of canvas elements. The user can edit/crop the images after they got resized, so I keep them as canvas instead of converting them to jpeg. (Which would worsen the initial performance)
Now this works fine, but I don't know what's the best way to actually upload the finished canvas elements to the server now. (Using a asp.net 4 generic handler on the server)
I have tried creating a json object from all elements containing the dataurl of each canvas.
The problem is, when I got 10-40 pictures, the browser starts freezing when creating the dataurls, especially for images that are larger than 2 megabyte.
//images = array of UploadImage
for (var i = 0; i < images.length; i++) {
var data = document.getElementById('cv_' + i).toDataURL('image/jpg');
images[i].data = data.substr(data.indexOf('base64') + 7);
}
Also converting them to a json object (I am using json2.js) usually crashes my browser. (FF7)
My object
var UploadImage = function (pFileName, pName, pDescription) {
this.FileName = pFileName;
this.Name = pName;
this.Description = pDescription;
this.data = null;
}
The upload routine
//images = array of UploadImage
for (var i = 0; i < images.length; i++) {
var data = document.getElementById('cv_' + i).toDataURL('image/jpg');
images[i].data = data.substr(data.indexOf('base64') + 7);
}
var xhr, provider;
xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (e) {
console.log(Math.round((e.loaded * 100) / e.total) + '% done');
}, false);
}
provider = function () {
return xhr;
};
var ddd = JSON.stringify(images); //usually crash here
$.ajax({
type: 'POST',
url: 'upload.ashx',
xhr: provider,
dataType: 'json',
success: function (data) {
alert('ajax success: data = ' + data);
},
error: function () {
alert('ajax error');
},
data: ddd
});
What would be the best way to send the canvas elements to the server?
Should I send them all at once or one by one?
Uploading files one by one is better. Requires less memory and as soon as one file ready to upload, the upload can be started instead of waiting while all files will be prepared.
Use FormData to send files. Allows to upload files in binary format instead of base64 encoded.
var formData = new FormData;
If Firefox use canvas.mozGetAsFile('image.jpg') instead of canvas.toDataUrl(). Allow to avoid unnecessary conversion from base64 to binary.
var file = canvas.mozGetAsFile('image.jpg');
formData.append(file);
In Chrome use BlobBuilder to convert base64 into blob (see dataURItoBlob function
accepted
After playing around with a few things, I managed to figure this out myself.
First of all, this will convert a dataURI to a Blob:
//added for quick reference
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
From this question):
var blob = dataURItoBlob(canvas.toDataURL('image/jpg'));
formData.append(blob);
And then send the formData object. I'm not sure how to do it in jQuery, but with plain xhr object it like so:
var xhr = new XMLHttpRequest;
xhr.open('POST', 'upload.ashx', false);
xhr.send(formData);
On server you can get files from Files collection:
context.Request.Files[0].SaveAs(...);

HTML5 File API XmlHttpRequest send(file) different than sending readAsBinaryString() result

I thought these two pieces of code (they work in Chrome and Firefox) were supposed to do the same thing, but they behave in different ways. They send the binary contents of a file via an XmlHttpRequest object.
Direct XHR send:
xhr.send(file);
Read file and send contents via XHR:
var reader = new FileReader();
reader.onload = function(event) {
xhr.send(event.target.result);
};
reader.readAsBinaryString(file);
File bytes sent do not match between requests (in the second one, the file is larger than in the first one, and the file gets corrupted).
I need to make the second option work.
Any ideas?
I ran into a similar problem - Corruption with FileReader into FormData
The reader's result is a string; you need to convert it into an array buffer:
var result = e.target.result;
var l = result.length
var ui8a = new Uint8Array(l)
for (var i = 0; i < l; i++)
ui8a[i] = result.charCodeAt(i);
var bb = new (window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder)()
bb.append(ui8a.buffer)
xhr.send(bb.getBlob())

Categories