I'm attempting to upload a file via drag and drop with HTML5. The dragging and dropping bit works no problem - I can get the image I drag to display immediately by dumping the base64 in an img src tag. However, I need to pass the file to the server via POST. In the same request, I also need to pass a unique ID. Here's what my processing function looks like:
function processXHR (file)
{
var xhr = new XMLHttpRequest();
var fileUpload = xhr.upload;
fileUpload.addEventListener("progress", uploadProgressXHR, false);
fileUpload.addEventListener("error", uploadErrorXHR, false);
xhr.open("POST", "changePicture");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", file.length);
xhr.sendAsBinary(file.getAsBinary());
xhr.setRequestHeader("Connection", "close");
}
However, doing this returns an error from codeigniter: "Disallowed Key Characters". Also, it's not sending the unique ID I need. So I changed a few lines:
var params = "card_num="+selected+"&newPicture="+file.getAsBinary();
xhr.open("POST", "changePicture");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.send(params);
xhr.setRequestHeader("Connection", "close");
But that just sends the file as a string. What do I need to be doing here?
function processXHR(file) {
var formData = new FormData();
var xhr = new XMLHttpRequest();
formData.append(file.name, file);
xhr.open('POST', "/upload", true);
xhr.onload = function(e) {
console.log("loaded!")
};
xhr.send(formData);
return false;
}
Obviously this only works in browsers that support XMLHttpRequest Level 2
Related
my web are built on flask
I enter page1 by GET , generate data then send the data back by XMLHttpRequest
POST in script of page1.html
var form = document.getElementById('process_form');
form.onsubmit = function (e) {
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open('POST', '/main/page1', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
var data = JSON.stringify(data);
xhr.send(data);
};
then I redirect to another page in page1 views
#process the data
redirect(url_for('main.page2'))
I can see the code of page2 view did execute and debug log
but the chrome browser still hold the page1,do not follow the redirect
I am using this
$.ajax({
type: "GET",
url: 'template/bump1/purse.png',
datatype:"image/png",
success: function (data) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.getElementById("CaptchaImg");
img.src = e.target.result;
};
reader.readAsDataURL(data);
//$('#CaptchaImg').attr('src', data);
}
});
to download an image, and it comes out in binary, looking like this
node.js is returning it as
WriteHeaderMode('image/png', res, 200);
res.end(data, 'binary');
But now, how do I put that into an image tag and show it as an image. Note: I do not want to have return data as base64 encoding, it has to be binary. Im fine with converting the binary into base64 on client side though.
When I pass it to the readAsDataURL, it says TypeError exception.
Thanks
EDIT
var img = document.getElementById("CaptchaImg");
var reader = new FileReader();
reader.onload = function(e) {
//img.src = e.target.result;
$("body").html(e.target.result);
};
reader.readAsDataURL(new Blob([data]));
this seems to convert it into a base64 encoding, which starts as data:application/octet-stream;base64, but doesn't display an image...
jQuery Ajax does not support binary responses(okay now it does), there is a trick that uses overrideMimeType('text/plain; charset=x-user-defined') to return each byte as a character in the response string and then to loop through the response to create a byte array of the data.
However with bare naked XMLHttpRequest this can be done easily with use of the responseType property.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
var img = document.getElementById("CaptchaImg");
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
xhr.open('GET', 'template/bump1/purse.png');
xhr.responseType = 'blob';
xhr.send();
Musa's answer is a great solution, I implemented something similar in angular and works great, when you define responseType = 'blob' your response won't be a string anymore, it will be a blob type object.
I just needed to add an extra parameter to the headers object (not sure if it's necessary in jQuery). headers: {'Content-Type': "image/png"},
My full request object:
var request = {
url: "_/get_image_/get",
method:"GET",
headers: {'Content-Type': "image/png"},
responseType: 'blob'
}
Try using new Blob(data, {type : 'image/png'}) instead of new Blob([data])
This will ensure that the media type of the blob is a png.
Source: https://developer.mozilla.org/en-US/docs/Web/API/Blob
Whatever framework/lib you're using:
When getting the image (a File), ask for a BLOB type
Use the following function to create a Blob and get an URL out of it
Set your image src to that URL
Code:
export function fileToImageBase64Url(file: File): string {
const blob = new Blob([file], { type: 'image/png' });
return URL.createObjectURL(blob);
}
If at some point you decide that the image is not useful anymore, don't forget to clean it: URL.revokeObjectURL(yourUrl)
I have this file thats created with html5, I am just starting to learn.
Basically when I am recording from the microphone and stop the record I am finding it hard to upload the outputted file to a folder on the server.
Here is the page i am testing on.
http://2click4.com/playground.php
You use Blob and createObjectURL in your code on example page. You create ObjectURL, so you can send it by XMLHttpRequest to server:
var blob = new Blob ( [ view ], { type : 'audio/wav' } );
// let's save it locally
outputElement.innerHTML = 'Handing off the file now...';
var url = (window.URL || window.webkitURL).createObjectURL(blob);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'link_to_server', true);
xhr.onload = function (e) {
var result = e.target.result;
};
xhr.send(url);//url is Blob
I'm creating a Google Chrome extension which use Google Drive API.
I have to upload a file with HTML5.
For text files, there is no problem. But when I want to upload a binary file, there are always errors.
So when I upload a file using the FileReader in HTML5 as BinaryString, my image is corrupted, I can't read it.
And when I use Base64 encoding (with the header in the body part "Content-Transfer-Encoding: base64"), I have a 400 Bad Request -> Malformed multipart body.
Can you help me please ?
Thanks :)
PS: I don't want to use Google Drive SDK, I prefer write all the code.
var bb, reader;
var meta = {
"title": "mozilla.png",
"mimeType": "image/png",
"description": "Mozilla Official logo"
};
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://developer.mozilla.org/media/img/mdn-logo-sm.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e){
if(this.status == 200){
bb = new WebKitBlobBuilder();
bb.append(this.response);
console.log('Download OK');
reader = new FileReader();
reader.readAsDataURL(bb.getBlob('image/png'));
reader.onloadend = function(e){
console.log('Reader OK');
var bound = 287032396531387;
var parts = [];
parts.push('--' + bound);
parts.push('Content-Type: application/json');
parts.push('');
parts.push(JSON.stringify(meta));
parts.push('--' + bound);
parts.push('Content-Type: image/png');
parts.push('Content-Transfer-Encoding: base64');
parts.push('');
parts.push(reader.result);
parts.push('--' + bound + '--');
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart", true);
xhr.setRequestHeader("Authorization", "Bearer token123456");
xhr.setRequestHeader("Content-Type", "multipart/mixed; boundary=" + bound);
xhr.onload = function(e){
console.log("DRIVE OK", this, e);
};
xhr.send(parts.join("\r\n"));
}
}
};
xhr.send();
For Binary Upload, just modify this line :
reader.readAsDataURL(bb.getBlob('image/png'));
by that
reader.readAsBinaryString(bb.getBlob('image/png'));
and delete this line :
parts.push('Content-Transfer-Encoding: base64');
I tried to create a file by sending the metadata first and upload the content after like in this post and I always get a 404 error for uploading the content, but this is another story...
An empty line which consists of only \r\n and no other whitespace need to be added at the end of your request. Try to add another parts.push(''); after parts.push('--' + bound + '--');
Edit:
First, I want to say that you should not upload file as raw Binary String because your binary data contains control characters which may screw up your request and results in corrupted file. Data should be encoded in Base64. You can read more here
If you check reader.result in debug, it will contain:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAD4AAABHCAMAAABoMgR/AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJlQTFRFAAAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAAwAAEgICExAQIAQFIyAgLwYHMjAwPggJQkBATAoLUlBQWwwOYmBgaQ4QcXBweBASgYCAhxIUkIKCkY+PlRQXoZ+fpBYZrYaGsK+vsxgbwL+/wRod0Bwg0M/P3h4i4N/f7SAk7+/v9pCS////7yG8VgAAAA90Uk5TABAgMEBQYHCAn6+/z9/vBoviEQAABBtJREFUWMOtmA13mzoMhumWdd3uWpuPACUEWIkXA3HI+P8/7kq2AYOBNj1Tz2nA9oOl10KAHUfZw+7p4/b41ZnY7j9yn708PQzww09yv7186+lf5FP2qHBJJ1y0H7am9JCR8z/BAa3bOy1B/zH+lzW6KJt3+CfHeYSfYqGboX9eylRMC5FB/7Pj/IBRdicPoTkOMMIgZWlAEmtIBn1fHFjx0JIGPQt40wiWSZGoZ/Mc2ncLuMgoABAQpXCWEi9hraAWv4KXFP1G1dIYBVSy1ha/iHOM12PzmdLU4hfwBhUj6VRKnqA/GfBxv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SrUAAAAASUVORK5CYII=
As you can see, the readAsDataURL method DID encode your data to base64 but because it is used to produce Data URI , a string with format as data:[<MIME-type>][;charset=<encoding>][;base64], is added at the begin of your encoded data. This is the culprit cause 400 Bad Request error (Malformed multipart body).The solution is to eliminate this string before adding it to the request body:
parts.push(reader.result.replace(/^data:image\/(png|jpg);base64,/, ""));
I have tested and it works fine.
I'm using HTML5 drag&drop to get images from a user's computer and want to upload them to my Rails server (using Carrierwave on that end). I don't know exactly what I'm doing here, but cobbled together this code from these instructions http://code.google.com/p/html5uploader/wiki/HTML5Uploader
This returns a 500 error - can anyone take a look and help me out with what I'm doing wrong?
var files = e.dataTransfer.files;
if (files.length){
for (var i = 0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
var bin = reader.result;
var xhr = new XMLHttpRequest();
var boundary = 'xxxxxxxxx';
xhr.open('POST', '/images?up=true&base64=true', true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
};
};
};
There are a couple of things that could be the culprit. You're reading the file as a binary string, then creating a multipart request, then sending a base64 encoded value.
There's no need to read the file or mess with base64 encoding. Instead, just construct a FormData object, append the file, and send that directly using xhr.send(formData). See my response here.