blob not storing any value for any reason - javascript

Recording a video with webRTC I have no data, and after debugging I just realized that there's no content in the Blob variable (that must store the video).
According to the code I pasted on my jsfiddle, line 136 should contain something like:
Blob {type: "audio/wav", size: 360492, slice: function}size: 360492type: "audio/wav"
But its value is undefined.
Could anybody tell me what am I doing wrongly?

You have to call stopRecording and get the blob within the callback. The callback will also be passed a data URL.
if (!isFirefox) {
recordAudio.stopRecording(function(dataURL){
var bloba = recordAudio.getBlob();
console.log("Audio Blob",bloba);
});
fileType = 'audio';
fileName = 'test.wav';
} else {
recordAudio.stopRecording(function(dataURL){
var bloba = recordAudio.getBlob();
console.log("Audio Blob",bloba);
});
fileType = 'video';
fileName = 'test.webm';
}
if (!isFirefox) {
recordVideo.stopRecording(function(dataURL){
var blobv = recordVideo.getBlob();
console.log("Video Blob",blobv);
});
fileType = 'video';
fileName = 'test.webm';
}
Updated Fiddle

Related

How to Convert Uploaded Audio to Blob using Javascript?

I am trying to capture the audio that's uploaded by the user, convert it to Blob then using wavesurfer.js to display the waveform.
I am following this instruction here https://bl.ocks.org/nolanlawson/62e747cea7af01542479
And here is the code
// Convert audio to Blob
$('#audioFileInput').on('change', function () {
var file = $('#audioFileInput')[0].files[0];
var fileName = file.name;
var fileType = file.type;
var fileReader = new FileReader();
fileReader.onloadend = function (e) {
var arrayBuffer = e.target.result;
blobUtil.arrayBufferToBlob(arrayBuffer, fileType).then(function (blob) {
console.log('here is a blob', blob);
console.log('its size is', blob.size);
console.log('its type is', blob.type);
surfTheBlob(blob);
}).catch(console.log.bind(console));
};
fileReader.readAsArrayBuffer(file);
});
But it says
blobUtil.arrayBufferToBlob(...).then is not a function
Another issue is that since the user might upload the audio themselves, the audio type might vary, expected to come from native device audio recorder. Anyone can help please? thanks.
A File object, like the ones you get in the input.files FileList, is already a Blob:
inp.onchange = e =>
console.log(inp.files[0] instanceof Blob) // true
<input type="file" id="inp">
So all you really need is to pass directly this File to your library:
$('#audioFileInput').on('change', function () {
var file = this.files[0];
surfTheBlob(file);
});
Found the answer already.
// Convert audio to Blob
$('#audioFileInput').on('change', function () {
var file = $('#audioFileInput')[0].files[0];
var fileName = file.name;
var fileType = file.type;
var url = URL.createObjectURL(file);
fetch(url).then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
}).then(function(blob) {
surfTheBlob(blob);
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
});
Cheers!

Saving file from blob:http using javascript with no redirection

I have already passed through some of the suggested solutions here in SO, but with no success. This is the problem. When the blob is generated using the data retrieved from the API endpoint, I want to force browser to download the blob. I have tried three solutions so far, but no of them works. Code follows. Notice that I put some comments in the code to explain further.
const FILE_NAME_REGEX = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
export function Download(url) {
return APICall.get(url).then(response => {
const disposition = response.request.getResponseHeader('Content-Disposition');
//^This line gives the 'Refused to get unsafe header "Content-Disposition"' error, so next few lines won't execute and part with generating anchor is not used, but the part of code under the 'else' branch.
if (disposition && disposition.indexOf('attachment') !== -1) {
const matches = FILE_NAME_REGEX.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
}
const type = response.request.getResponseHeader('Content-Type');
const blob = new Blob([response.data], { type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
const URL = window.URL || window.webkitURL;
const downloadUrl = URL.createObjectURL(blob);
if (filename) {
const a = document.createElement('a');
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
} else {
// 1. soultion
window.location = downloadUrl;
}
setTimeout(() => {
URL.revokeObjectURL(downloadUrl);
}, 100);
}
});
}
// 2. solution
const ifrmDownloader = document.createElement('iframe');
ifrmDownloader.setAttribute('src', downloadUrl);
ifrmDownloader.style.width = '0px';
ifrmDownloader.style.height = '0px';
document.body.appendChild(ifrmDownloader);
// 3. solution
window.open(downloadUrl,_blank);
Solution does not work because it opens another tab and returns empty little square instead of the file. This is probably due to the lost temp blob when new tab got opened.
Solution simply does not work, and I do not know why. Iframe gets added to the dom and request is recorded in the Network tab under developer console, but no download is trigerred. Probably the same reason as in the solution 1. In addition this message is logged:
Resource interpreted as Document but transferred with MIME type image/png: "blob:https://example.com/e53bf47b-7f39-4758-b3dd-3cc2df5889ad".
Solution does not work as well. First of, browser blocked pop up, and after te pop up is allowed, no file download is initiated.
I feel that something is missing here, but what?
Your code is set up to download the File only when the filename variable is set.
This variable is set only when you are able to read the Content-Disposition header (i.e only when same-origin).
So the simple fix would be to set a dummy value for filename when you failed to get it from the Headers, this way, filename is always set, and you always try to download it insted of just opening it in a new page.
The smarter fix would be to try to parse the filename from the url variable, but without knowing the format of possible urls, it's hard to make one for you.
const FILE_NAME_REGEX = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
export function Download(url) {
return APICall.get(url).then(response => {
const disposition = response.request.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
const matches = FILE_NAME_REGEX.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
}
if (!filename) {
// getFileNameFromURL(url);
filename = 'dummy.png';
}
const type = response.request.getResponseHeader('Content-Type');
const blob = new Blob([response.data], {
type
});
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
const URL = window.URL || window.webkitURL;
const downloadUrl = URL.createObjectURL(blob);
// if (filename) { // always truthy
const a = document.createElement('a');
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
// }
/* else { // useless
window.location = downloadUrl;
}
*/
setTimeout(() => {
URL.revokeObjectURL(downloadUrl);
}, 100);
}
});
}
Here is what I have found in regards to the problem I posted. There were two problems actually:
Content-Disposition header was getting refused and therefore no filename nor the dispostion information were available. This was bridged according to #Kaiido's reply, by extracting the filename from the url and adding ',png'. E.G.
const chunks = extendedURl.split('/');
const pngExtension = '.png';
const baseName = chunks[chunks.length - 1].split('?')[0];
filename = `${baseName}${pngExtension}`;
More serious problem that I did not realize until today was that when axios' Get method was called, responseType was not set to 'arraybuffer'.
Therefore, I was able to download files that were 'broken'. This question helped me figure out where the actual problem was: File is corrupted while downloading using angular $http
Once the calling Get method was provided with the 'responseType: "arraybuffer"', files started to appear normal, not 'broken'.
To sum it up, when calling .net Core Web API endpoint that returns FileStreamResult, in order to be able to create Blob in your FE JavaScript, you should explicitly set responseType to 'arraybuffer' as follows:
axios.get(extendedURl, { responseType: 'arraybuffer' }).then(response =>...

create and automatically force download file using js

I have used HTML file reader API to read the file,
and i got the below result
data:application/pdf;base64,JVBERi0xLjYNJeLjz9MNCjE2OSAwIG9iaiA8PC9MaW5lYXJpemVkIDEvTCAyMDgwNTMxL08gMTczL0UgMjg1ODM3L04gMjQvVCAyMDc3MDkyL0ggWyAxMTM2IDc1OV0+Pg1lbmRvYmoNICAgICAgICAgIA14cmVmDTE2OSA0Mg0wMDAwMDAwMDE2IDAwMDAwIG4NCjAwMDAwMDE4OTUgMDAwMDAgbg0KMDAwMDAwMjAzMSAwMDAwMCBuDQowMDAwMDAyMTY0IDAwMDAwIG4NCjAwMDAwMDIzMTkgMDAwMDAgbg0KMDAwMDAwMjgzOCAwMDAwMCBuDQowMDAwMDAyODY0IDAwMDAwIG4NCjAwMDAwMDM3OTAgMDAwMDAgbg0KMDAwMDAwNDMyNCAwMDAwMCBuDQowMDAwMDA0NDE1IDAwMDAwIG4NCjAwMDAwMDU2MDcgMDAwMDAgbg0KMDAwMDAwNTY1MiAwMDAwMCBuDQowMDAwMDA1Njc3IDAwMDAwIG4NCjAwMDAwMDU3OTUgMDAwMDAgbg0KMDAwMDAwNTg0NSAwMDAwMCBuDQowMDAwMDA1ODcwIDAwMDAwIG4NCjAwMDAwMDU5ODYgMDAwMDAgbg0KMDAwMDAwNzQxOSAwMDAwMCBuDQowM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MDAwIG4NCjAwMDIwNzAzMTcgMDAwMDAgbg0KMDAwMjA3MDM3NSAwMDAwMCBuDQowMDAyMDcwNDk5IDAwMDAwIG4NCjAwMDIwNzA1MzEgMDAwMDAgbg0KMDAwMjA3MDU1MiAwMDAwMCBuDQowMDAyMDcwNTc4IDAwMDAwIG4NCjAwMDIwNzY4NDMgMDAwMDAgbg0KdHJhaWxlcg08PC9TaXplIDE2OS9FbmNyeXB0IDE3MCAwIFI+Pg1zdGFydHhyZWYNMTE2DSUlRU9GDQ==
How to write a file and force download the same file using the above string?
Warning: I don't have IE available to test with, but this was based off code that DOES work under IE.
My DataURL is an image so I had to change out the header. You might not have to with your header -- but I left the code in place so you could see how it was done.
Thanks to IE, you need two different processes.
On IE, you convert your DataURI to a blob then download the blob.
On everything else, you would just download the URI itself.
document.getElementById("d_button").addEventListener("click", download);
var filename="testfile";
// FROM http://stackoverflow.com/questions/12168909/blob-from-dataurl
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {
type: mimeString
});
return blob;
// Old code
// var bb = new BlobBuilder();
// bb.append(ab);
// return bb.getBlob(mimeString);
}
const dataURI = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
function download() {
if (window.navigator.msSaveBlob) { // for IE
const blob = dataURItoBlob(dataURI);
window.navigator.msSaveBlob(blob, `${filename}.png`);
return;
}
let dt = dataURI;
/* Change MIME type to trick the browser to downlaod the file instead of displaying it */
dt = dt.replace(/^data:image\/[^;]*/, "data:application/octet-stream");
/* In addition to <a>'s "download" attribute, you can define HTTP-style headers */
dt = dt.replace(/^data:application\/octet-stream/, `data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=${filename}.png`);
this.href = dt;
}
Download this
I got answer using <a> tag force the download the file.
var element = document.createElement('a');
element.setAttribute('href',text );
element.setAttribute('download', filename);
element.setAttribute('target', '_blank');
element.style.display = 'none';
document.body.appendChild(element);
$("#page_header").removeClass('loader');
element.click();
I got another answer using force the download the file.
using this link install file saver (https://www.npmjs.com/package/file-saver)
result : 'data:application/pdf;base64,JVBERi0xLjYNJeLjz9MNCjE2OSAwIG9iaiA8PC9MaW5lYXJpemVkIDEvTCAyMDgwNTMxL08gMTczL0UgMjg1ODM3L04gMjQvVCAyMDc3MDkyL0ggWyAxMTM2IDc1OV0+Pg1lbmRvYmoNICAgICAgICAgIA14cmVmDTE2OSA0Mg0wMDAwMDAwMDE2IDAwMDAwIG4NCjAwMDAwMDE4OTUgMDAwMDAgbg0KMDAwMDAwMjAzMSAwMDAwMCBuDQowMDAwMDAyMTY0IDAwMDAwIG4NCjAwMDAwMDIzMTkgMDAwMDAgbg0KMDAwMDAwMjgzOCAwMDAwMCBuDQowMDAwMDAyODY0IDAwMDAwIG4NCjAwMDAwMDM3OTAgMDAwMDAgbg0KMDAwMDAwNDMyNCAwMDAwMCBuDQowMDAwMDA0NDE1IDAwMDAwIG4NCjAwMDAwMDU2MDcgMDAwMDAgbg0KMDAwMDAwNTY1MiAwMDAwMCBuDQowMDAwMDA1Njc3IDAwMDAwIG4NCjAwMDAwMDU3OTUgMDAwMDAgbg0KMDAwMDAwNTg0NSAwMDAwMCBuDQowMDAwMDA1ODcwIDAwMDAwIG4NCjAwMDAwMDU5ODYgMDAwMDAgbg0KMDAwMDAwNzQxOSAwMDAwMCBuDQowMDAwMDA3Nzk4IDAwMDAwIG4NCjAwMDAwMDgxMDQgMDAwMDAgbg0KMDAwMDAwODQxMyAwMDAwMCBuDQowMDAwMDA4OTQ0IDA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wNzA1MzEgMDAwMDAgbg0KMDAwMjA3MDU1MiAwMDAwMCBuDQowMDAyMDcwNTc4IDAwMDAwIG4NCjAwMDIwNzY4NDMgMDAwMDAgbg0KdHJhaWxlcg08PC9TaXplIDE2OS9FbmNyeXB0IDE3MCAwIFI+Pg1zdGFydHhyZWYNMTE2DSUlRU9GDQ=='
file_name : 'sample.jpg'
fileType : 'image/jpeg'
**Function Call**
this.urltoFile(result, file_name, fileType)
.then(function(file){
var blob = new Blob ([file], {type: fileType});
FileSaver.saveAs(blob, file_name);
this.loading = false;
});
**function definition**
urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
)},

URL encoding "data:image/jpg; base64" image

How can I encode the data:image/jpeg;base64 data url to be transmitted correctly through an AJAX POST. I have the following code xhr.open('POST', 'http://url-sent-to/image/' + saveImage + '&imageid=' + imageid.value, true); that is doing so now.
However, the URL http://url-sent-to/image/data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…RRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/2Q==&imageid=testimagedata does not look like it will be correct, especially since it has = in it.
$(function () {
var fileInput = document.getElementById("file")
, renderButton = $("#renderButton")
, imgly = new ImglyKit({
container: "#container",
ratio: 1 / 1
});
// As soon as the user selects a file...
fileInput.addEventListener("change", function (event) {
var file;
var fileToBlob = event.target.files[0];
var blob = new Blob([fileToBlob], {"type":fileToBlob.type});
// do stuff with blob
console.log(blob);
// Find the selected file
if(event.target.files) {
file = event.target.files[0];
} else {
file = event.target.value;
}
// Use FileReader to turn the selected
// file into a data url. ImglyKit needs
// a data url or an image
var reader = new FileReader();
reader.onload = (function(file) {
return function (e) {
data = e.target.result;
// Run ImglyKit with the selected file
try {
imgly.run(data);
} catch (e) {
if(e.name == "NoSupportError") {
alert("Your browser does not support canvas.");
} else if(e.name == "InvalidError") {
alert("The given file is not an image");
}
}
};
})(file);
reader.readAsDataURL(file);
});
// As soon as the user clicks the render button...
// Listen for "Render final image" click
renderButton.click(function (event) {
var dataUrl;
imgly.renderToDataURL("image/jpeg", { size: "1200" }, function (err, dataUrl) {
// `dataUrl` now contains a resized rendered image with
// a width of 300 pixels while keeping the ratio
//Convert DataURL to Blob to send over Ajax
function dataURItoBlob(dataUrl) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataUrl.split(',')[1]);
// separate out the mime component
var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
//var bb = new BlobBuilder();
//bb.append(ab);
//return bb.getBlob(mimeString);
}
var blob = dataURItoBlob(dataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
var saveImage = dataUrl;
//console.log(saveImage);
fd.append("myFile", blob);
xhr.open('POST', 'http://url-sent-to/image/' + saveImage + '&imageid=' + imageid.value, true);
xhr.send(fd);
I have a fiddle setup for an example of what I'm doing. Essentially, the user will select an image, enter a description, and hit render. When you check the Javascript console, you'll see a Blob is created, and the POST message at the bottom: http://jsfiddle.net/mattography/Lgduvce1/2/
You're looking for encodeURI(), which will do exactly what you're looking for.
Note that you're missing a ? to start your querystring.
Also note that making URLs that long is a bad idea; you should send a POST request instead.

Create a download link from a Blob URL

In a Google chrome extension I am working on, a file is downloaded from a server with an XMLHttpRequest. This file contains some binary data which are stored in an ArrayBuffer object. In order to provide the possibility to download this file I am using the createObjectURL API.
function publish(data) {
if (!window.BlobBuilder && window.WebKitBlobBuilder) {
window.BlobBuilder = window.WebKitBlobBuilder;
}
var builder = new BlobBuilder();
builder.append(data);
var blob = builder.getBlob();
var url = window.webkitURL.createObjectURL(blob);
$("#output").append($("<a/>").attr({href: url}).append("Download"));
}
It is working fine; except that the filename is an opaque UUID like 9a8f6a0f-dd0c-4715-85dc-7379db9ce142. Is there any way to force this filename to something more user-friendly?
you can force an arbitrary filename by setting the "download" attribute of your anchor
see: http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download
I have never tried it before, but it should be possible to create a new File object (which allows you to specify a file name) and write your blob to it. Something along the lines of:
function publish(data, filename) {
if (!window.BlobBuilder && window.WebKitBlobBuilder) {
window.BlobBuilder = window.WebKitBlobBuilder;
}
fs.root.getFile(filename, {
create: true
}, function (fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
console.log('Write completed.');
};
fileWriter.onerror = function (e) {
console.log('Write failed: ' + e.toString());
};
var builder = new BlobBuilder();
builder.append(data);
var blob = builder.getBlob();
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
}
I think this could work for you.

Categories

Resources