I'm trying to use filepicker.io to fetch binary data and pass it into a function like this:
var doSomething = function(arrayBuffer) {
var u16 = new Int16Array(arrayBuffer);
}
I have no idea how to convert the binary into arraybuffer like this:
filepicker.getContents(url, function(data){
//convert data into arraybuffer
}
I tried to follow this tutorial on XMLHttpRequest but does't not work.
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
doSomething(this.response);
};
You are not calling .send with your XHR
xhr.send(null);
Related
I would like to download completely a mp4 video from an Ajax request in order to render it later.
With an asynchronous request, it works correctly :
const req = new XMLHttpRequest();
req.open('GET', myVideoUrl, true);
req.responseType = 'blob';
req.onload = function() {
renderVideo(URL.createObjectURL(this.response));
};
But I would prefer to do it synchronously in order to block the rendering until the video is downloaded. I tried this way, but it doesn't work...
const req = new XMLHttpRequest();
req.open('GET', myVideoUrl, false);
req.send(null);
const blob = new Blob([req.responseText], { type: 'video/mp4' });
renderVideo(URL.createObjectURL(blob));
I think the problem comes from the binary data and the conversion I tried from responseText to objectUrl...
Any idea to resolve that ?
I have a function that allows me to pass file content, name, and type and the function will automatically save it. It works great for text based documents, but now I'm trying to have it save other files, like an image file. Somewhere along the line its getting corrupted and isn't working.
function write(text, filename, mime){
var file = new Blob([text], {type:mime}), a = document.createElement('a');
// Download in IE
if(window.navigator.msSaveBlob) window.navigator.msSaveBlob(file, filename);
// Download in compliant browsers
else{
var url = URL.createObjectURL(file);
a.href = url, a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function(){
document.body.removeChild(a);
window.URL.revokeObjectURL(url);}, 0);}}
write('Plain text', 'demo.txt', 'text/plain');
write(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAAdCAIAAADkY5E+AAAAD0lEQVR42mNg0AthoDMGAE1BDruZMRqXAAAAAElFTkSuQmCC'), 'demo.png', 'image/png');
FileSaver.js a very powerfull js script to save any type of blob file.
Import it then use it like that:
saveAs(new Blob([file], {type:mime}),filename);
Are you fetching the file using ajax? if so, you should set
XmlHttpRequest.responseType to 'arraybuffer' or 'blob' (default is '' and that will not work with binaries or blob data).
Working example (using arraybuffer) (Fiddle):
var xhr = new XMLHttpRequest();
var url = 'https://upload.wikimedia.org/wikipedia/commons/d/da/Internet2.jpg';
xhr.responseType = 'arraybuffer'; //Set the response type to arraybuffer so xhr.response returns ArrayBuffer
xhr.open('GET', url , true);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
//When request is done
//xhr.response will be an ArrayBuffer
var file = new Blob([xhr.response], {type:'image/jpeg'});
saveAs(file, 'image.jpeg');
}
};
xhr.send(); //Request is sent
Working example 2 (using blob) (Fiddle):
var xhr = new XMLHttpRequest();
var url = 'https://upload.wikimedia.org/wikipedia/commons/d/da/Internet2.jpg';
xhr.responseType = 'blob'; //Set the response type to blob so xhr.response returns a blob
xhr.open('GET', url , true);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
//When request is done
//xhr.response will be a Blob ready to save
saveAs(xhr.response, 'image.jpeg');
}
};
xhr.send(); //Request is sent
I recommend FileSaver.js to save the blobs as files.
Useful links:
XmlHttpRequest Standard
XmlHttpRequest Standard (responseType attribute)
MDN Docs (XmlHttpRequest)
MDN Docs (ArrayBuffer)
I want to get a Base64 encoded file from the server in order to use it in a dataURL so I use:
xhr.overrideMimeType("text/plain; charset=x-user-defined");
So I get the unprocessed data to perform the base64 encoding on.
But I also want to get the mimetype originally returned from the server to declare my dataURL:
var dataUrl = 'data:'+mimetype+';base64,'+b64;
when I try something like the following:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
var mimetype = xhr.getResponseHeader('content-type');
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
the content-type returned is always null
Full source:
function getFileDataUrl(link,mimetype)
{
var url = location.origin+link;
var getBinary = function (url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
if(mimetype == null)
{
mimetype = xhr.getResponseHeader('content-type');
console.log('mimetype='+mimetype);
}
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
return xhr.responseText;
};
var bin = getBinary(url);
var b64 = base64Encode(bin);
var dataUrl = 'data:'+mimetype+';base64,'+b64;
return dataUrl;
}
var dataUrl = getFileDataUrl(link,null);
You can set responseType of XMLHttpRequest to "blob" or "arraybuffer" then use FileReader, FileReader.prototype.readAsDataURL() on response. Though note, onload event of FileReader returns results asynchronously. To read file synchronously you can use Worker and FileReaderSync()
var reader = new FileReader();
reader.onload = function() {
// do stuff with `reader.result`
console.log(reader.result);
}
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
reader.readAsDataURL(xhr.response);
}
xhr.send(null);
At chromium synchronous XMLHttpRequest() is deprecated, see https://xhr.spec.whatwg.org/.
You can use Promise at main thread to get data URI of requested resource using either Worker or when FileReader load event is dispatched. Or use synchronous XMLHttpRequest() and FileReaderSync() at Worker thread, then listen for message event at main thread, use .then() to get Promise value.
Main thread
var worker = new Worker("worker.js");
var url = "path/to/resource";
function getFileDataUrl(url) {
return new Promise(function(resolve, reject) {
worker.addEventListener("message", function(e) {
resolve(e.data)
});
worker.postMessage(url);
})
}
getFileDataUrl(url)
.then(function(data) {
console.log(data)
}, function(err) {
console.log(err)
});
worker.js
var reader = new FileReaderSync();
var request = new XMLHttpRequest();
self.addEventListener("message", function(e) {
var reader = new FileReaderSync();
request.open("GET", e.data, false);
request.responseType = "blob";
request.send(null);
self.postMessage(reader.readAsDataURL(request.response));
});
plnkr http://plnkr.co/edit/gayWpkTVydmKYMnPr3jD?p=preview
I am trying to upload a image to server,In that i have converted image to base64encode string and i need to pass that base64encode string to webservice,that webservice convert the base64 string to file and saving in database.but base64encode string has huge length approximately(85,000) when i pass this string to webservice i am getting the following error.
Failed to load resource: the server responded with a status of 400 (Bad Request)
i need to pass this by using only XMLHttpRequest() with out using the ajax,jquery please help me.
below is my code.
var filesToBeUploaded = document.getElementById("afile");
var file = filesToBeUploaded.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var binaryStringResult = reader.result;
var binaryString =binaryStringResult.split(',')[1];
var xhr = new XMLHttpRequest();
xhr.open("POST","http://url/api/jsonws/Global-portlet.org_roles/add-file-entry?repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString);
xhr.setRequestHeader("Authorization","BasicbmFyYXlhbmFAdmlkeWF5dWcuY29tOnRlc3Q=");
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send();
xhr.onload = function() {
alert('in sucess');
};
xhr.onerror = function(e) {
alert('in error');
};
}
reader.readAsDataURL(file);
For POST, don't include it in the URL, you need to put it in the body, i.e.
xhr.send(binaryString);
I doubt your Content-Type of application/x-www-form-urlencoded is correct in this case.
I think the issue that you encountering here is that you are exceeding the maximum length of a query string.
What you need to do is something like the following:
var xhr = new XMLHttpRequest();
var url = "http://url/api/jsonws/Global-portlet.org_roles/add-file-entry";
var params = "repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
Hope that helps
Link given:
example.com/data/videos/videoname.mp4
How to pass this link as fileInput?
var fileUrl = window.URL.createObjectURL(fileInput);
All should be done in javascript only.
Need a solution in pure javascript only not using any jquery.
You can use ajax and get blob
var url = 'http://example.com/data/videos/videoname.mp4';
var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:'+url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var myObject = this.response;
}
};
xhr.send();