Show video blob after reading it through AJAX - javascript

While I was trying to create a workaround for Chrome unsupporting blobs in IndexedDB I discovered that I could read an image through AJAX as an arraybuffer, store it in IndexedDB, extract it, convert it to a blob and then show it in an element using the following code:
var xhr = new XMLHttpRequest(),newphoto;
xhr.open("GET", "photo1.jpg", true);
xhr.responseType = "arraybuffer";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
newphoto = xhr.response;
/* store "newphoto" in IndexedDB */
...
}
}
document.getElementById("show_image").onclick=function() {
var store = db.transaction("files", "readonly").objectStore("files").get("image1");
store.onsuccess = function() {
var URL = window.URL || window.webkitURL;
var oMyBlob = new Blob([store.result.image], { "type" : "image\/jpg" });
var docURL = URL.createObjectURL(oMyBlob);
var elImage = document.getElementById("photo");
elImage.setAttribute("src", docURL);
URL.revokeObjectURL(docURL);
}
}
This code works fine. But if I try the same process, but this time loading a video (.mp4) I can't show it:
...
var oMyBlob = new Blob([store.result.image], { "type" : "video\/mp4" });
var docURL = URL.createObjectURL(oMyBlob);
var elVideo = document.getElementById("showvideo");
elVideo.setAttribute("src", docURL);
...
<video id="showvideo" controls ></video>
...
Even if I use xhr.responseType = "blob" and not storing the blob in IndexedDB but trying to show it immediately after loading it, it still does not works!
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
newvideo = xhr.response;
var docURL = URL.createObjectURL(newvideo);
var elVideo = document.getElementById("showvideo");
elVideo.setAttribute("src", docURL);
URL.revokeObjectURL(docURL);
}
}
The next step was trying to do the same thing for PDF files, but I'm stuck with video files!

This is a filler answer (resolved via the OP found in his comments) to prevent the question from continuing to show up under "unanswered" questions.
From the author:
OK, I solved the problem adding an event that waits for the
video/image to load before executing the revokeObjectURL method:
var elImage = document.getElementById("photo");
elImage.addEventListener("load", function (evt) { URL.revokeObjectURL(docURL); }
elImage.setAttribute("src", docURL);
I suppose the revokeObjectURL method was executing before the video
was totally loaded.

Related

JS FileSaver non interactive

I have an array of file to save by using a loop and i generate the name of each file. I want to save file directly (in non interactive way) without asking me to confirm. How can i do ?
Here is my code for saving file
var url = img.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
var xhr = new XMLHttpRequest();
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) {
var filesaver = require('file-saver');
filesaver.saveAs(xhr.response, nameFile); // nameFile the name of file to be saved
}
};
xhr.send(); //Request is sent
Finally, i find a solution, instead of saving file, i write it by creating a new one.
for (var i = 0; i < tabForm.length; i++) {
var imgData = $('#affichageqr')[0].childNodes[1].childNodes[0].src;
var data = imgData.replace(/^data:image\/\w+;base64,/, '');
fs.writeFile(qrcode.getNomQRCode()+'.jpeg', data, {encoding: 'base64'}, function(err){
if (err) {
console.log('err', err);
}
console.log('success');
});
}

Can I create a growing file source URL which is not a video/audio Type?

I have read this article, but this is a video's solution.
Now, I want create a non vidoe/audio sourceBuffer url. I don't know how to implement it. I think that maybe mediasource is not support.
<script>
var ms = new MediaSource();
var src = window.URL.createObjectURL(ms);
console.log(src);
// sourceopen is not work.
// I don't know if i can create a non audio/video type growing file url?
ms.addEventListener('sourceopen', function(e) {
var sourceBuffer = ms.addSourceBuffer('application/octet-stream');
var xhr = new XMLHttpRequest();
xhr.open('GET', '/test.bin', true); // just a binary content
xhr.responseType = 'arraybuffer';
xhr.send();
xhr.onload = function() {
if (xhr.status >= 400) {
alert('Unexpected status code ' + xhr.status);
return false;
}
sourceBuffer.appendBuffer(xhr.response);
};
}, false);
</script>

Can't get EXIF info using loadImage.parseMetaData

I am using JavaScript LoadImage.parseMetaData (https://github.com/blueimp/JavaScript-Load-Image) to try and get Orientation of an image on the web, so I can rotate it.
If I hardcode the orientation (see "orientation: 3" in my second loadImage call), I can rotate it... but I am trying to use loadImage.parseMetaData to get the Orientation.
I have used web based EXIF parsers and the orientation info is there in the image.
When I call loadImage.parseMetaData "data.exif" seems to be null. See this fiddle: http://jsfiddle.net/aginsburg/GgrTM/13/
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.filepicker.io/api/file/U0D9Nb9gThy0fFbkrLJP', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
// Note: .response instead of .responseText
console.log ("got image");
var blob = new Blob([this.response], {type: 'image/png'});
console.log("about to parse blob:" + _.pairs(this.response));
loadImage.parseMetaData(blob, function (data) {
console.log("EXIF:" + _.pairs(data))
var ori ="initial";
if (data.exif) {
ori = data.exif.get('Orientation');
}
console.log("ori is:" + ori);
});
var loadingImage = loadImage(
blob,
function (img) {
console.log("in loadingImage");
document.body.appendChild(img);
},
{maxWidth: 600,
orientation: 3,
canvas: true,
crossOrigin:'anonymous'
}
);
if (!loadingImage) {
// Alternative code ...
}
}
};
xhr.send();
Any ideas or alternative approaches to correctly orientating images welcome.
Your call to loadImage needs to be inside the callback from the call to parseMetaData.
The reason: as is, your code contains a race condition. The call the loadImage is very likely to be made BEFORE the call the parseMetaData completes and stuffs the orientation due to the fact they are both asynchronous calls.
Why are you making a new blob whereas you asked for a Blob? The metadata are then lost, this is why you are losing it and exif is null.
Just replace :
var blob = new Blob([this.response], {type: 'image/png'});
By:
var blob = this.response;
Should do the trick.
Had the same problem, I changed the reponse type for 'arrayBuffer' and then create the blob from the response
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
if (this.status == 200) {
var arrayBufferView = new Uint8Array(this.response);
var blob = new Blob([arrayBufferView], { type: "image/jpeg" });
...

html5 multiple xmlhttprequest more response

Hi guys!
I've got a little problem with my HTML5 XMLHttprequest uploader.
I read files with Filereader class from multiple file input, and after that upload one at the time as binary string. On the server I catch the bits on the input stream, put it in tmp file, etc. This part is good. The program terminated normally, send the response, and I see that in the header (eg with FireBug).
But with the JS, I catch only the last in the 'onreadystatechange'.
I don't see all response. Why? If somebody can solve this problem, it will be nice :)
You will see same jQuery and Template, don't worry :D
This is the JS:
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object
var todo = {
progress:function(p){
$("div#up_curr_state").width(p+"%");
},
success:function(r,i){
$("#img"+i).attr("src",r);
$("div#upload_state").remove();
},
error:function(e){
alert("error:\n"+e);
}
};
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
var row = $('ul#image_list li').length;
row = row+i;
// Closure to capture the file information.
reader.onload = (function(theFile,s) {
return function(e) {
// Render thumbnail.
$("span#prod_img_nopic").hide();
$("div#prod_imgs").show();
var li = document.createElement('li');
li.className = "order_"+s+" active";
li.innerHTML = ['<img class="thumb" id="img'+s+'" src="', e.target.result,
'" title="', escape(theFile.name), '"/><div id="upload_state"><div id="up_curr_state"></div>Status</div>'].join('');
document.getElementById('image_list').insertBefore(li, null);
};
})(f,row);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
//upload the data
//#param object fileInputId input file id
//#param int fileIndex index of fileInputId
//#param string URL url for xhr event
//#param object todo functions of progress, success xhr, error xhr
//#param string method method of xhr event-def: 'POST'
var url = '{/literal}{$Conf.req_admin}{$SERVER_NAME}/{$ROOT_FILE}?mode={$_GET.mode}&action={$_GET.action}&addnew=product&imageupload={literal}'+f.type;
upload(f, row, url, todo);
}
the upload function:
function upload(file, fileIndex, Url, todo, method)
{
if (!method) {
var method = 'POST';
}
// take the file from the input
var reader = new FileReader();
reader.readAsBinaryString(file); // alternatively you can use readAsDataURL
reader.onloadend = function(evt)
{
// create XHR instance
xhr = new XMLHttpRequest();
// send the file through POST
xhr.open(method, Url, true);
// make sure we have the sendAsBinary method on all browsers
XMLHttpRequest.prototype.mySendAsBinary = function(text){
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0);
for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
bb.append(data);
var blob = bb.getBlob();
this.send(blob);
}
// let's track upload progress
var eventSource = xhr.upload || xhr;
eventSource.addEventListener("progress", function(e) {
// get percentage of how much of the current file has been sent
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
// here you should write your own code how you wish to proces this
todo.progress(percentage);
});
// state change observer - we need to know when and if the file was successfully uploaded
xhr.onreadystatechange = function()
{
if(xhr.status == 200 && xhr.readyState == 4)
{
// process success
resp=xhr.responseText;
todo.success(resp,fileIndex);
}else{
// process error
todo.error(resp);
}
};
// start sending
xhr.mySendAsBinary(evt.target.result);
};
}
}
}
and the starter event
document.getElementById('files').addEventListener('change', handleFileSelect, false);
It's a quite small mistake: You forgot to add a var statement:
// create XHR instance
var xhr = new XMLHttpRequest();
// ^^^ add this
With a readystatechange handler function like yours
function() {
if (xhr.status == 200 && xhr.readyState == 4) {
resp=xhr.responseText; // also a missing variable declaration, btw
todo.success(resp,fileIndex);
} else {
todo.error(resp);
}
}
only the latest xhr instance had been checked for their status and readyState when any request fired an event. Therefore, only when the last xhr triggers the event itself the success function would be executed.
Solution: Fix all your variable declarations, I guess this is not the only one (although affecting the behaviour heavily). You also might use this instead of xhr as a reference to the current XMLHttpRequest instance in the event handler.

Running JavaScript downloaded with XMLHttpRequest

I have a site that loads information using the XMLHttpRequest when a user clicks a link. The system works well but I would like to be able to execute JavaScript gathered in this process.
This is a problem as I would like to download the scripts 'on demand' if it were, rather than loading them all when the page is loaded.
Thanks for any help
I believe the recommended solution is something like this:
function include(scriptUrl)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", scriptUrl);
xmlhttp.onreadystatechange = function()
{
if ((xmlhttp.status == 200) && (xmlhttp.readyState == 4))
{
eval(xmlhttp.responseText);
}
};
xmlhttp.send();
}
Or something like it.
However, be wary of this approach. It's vulnerable to cross-site scripting, which can open you (and your users) up to all sorts of nastiness. You'll want to take suitable precautions.
Recently I found the answer (It works in Chrome, in another browsers it was not tested).
You can create dataURL string and put it into src attribute of script element.
var xhr = XMLHttpRequest(),
doc = document;
xhr.open('GET', pathToJSFile, true);
xhr.onload = function () {
var script = doc.createElement('script'),
base64 = 'data:application/javascript;base64,';
try {
base64 += btoa(data.responseText);
} catch (e) {
// script file may contain characters that not included in Latin1
var symbols = data.responseText.split('');
for (var i = 0, l = symbols.length; i < l; i++) {
var symbol = symbols[i];
// here we are trying to find these symbols in catch branch
try {
btoa(symbol);
} catch (e) {
var code = symbol.charCodeAt(0).toString(16);
while (code.length < 4) {
code = '0' + code;
}
// replace original symbol to unicode character
symbols[i] = '\\u' + code;
}
}
// create new base64 string from string with replaced characters
base64 += btoa(symbols.join(''));
} finally {
script.src = base64;
// run script
doc.body.appendChild(script);
}
};
xhr.send();
You can subscribe to xhr.onprogress to show progress bar.
Update. You can download your script file as blob, and then create blob-url.
var xhr = XMLHttpRequest(),
doc = document;
xhr.responseType = 'blob';
xhr.open('GET', pathToJSFile, true);
xhr.onload = function () {
var script = doc.createElement('script'),
src = URL.createObjectURL(xhr.response);
script.src = src;
doc.body.appendChild(script);
};
xhr.send();
You can run script downloaded in form of a string using
eval()
However I would recommend you to add new
<script src='..'></script>
to your document and have a callback which will be called when it will be downloaded. There are many utils and jquery plug-ins for that.
I had the challenge on a mobile web-project, the magic was to set "overrideMimeType".
This has been verified to work on Android 4.1 to Android 6.0.
var head = document.getElementsByTagName('head');
var injectedScript = document.createElement('script');
head[0].appendChild(injectedScript);
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
injectedScript.innerHTML = myRequest.responseText;
//run a function in the script to load it
}
};
function start(){
myRequest.open('GET', 'javascript-url-to-download', true);
myRequest.overrideMimeType('application/javascript');
myRequest.send();
}
start();
You would need to use eval to parse the javascript from the XHR, note that this is EXTREMELY dangerous if you don't have absolute trust in the source of the javascript.

Categories