In our app we have the following HTML code
<audio controls="controls" src="http://user:password#server:port/searchapi?command=replay&id=9203732824369002191_2"> Your browser does not support the HTML5 Audio element. </audio>
It goes to the URL above and supposed to get an audio file.
However, it's not supported in every browser, so we decided to do the following:
Instead of that authorization execute JS code which sends a GET request
In a src attribute put the file itself.
The code looks like this:
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'server:port/searchapi?command=replay&id=9203732824369002191_2', false);
myRequest.setRequestHeader('Authorization', 'Basic ' + btoa('user:password'));
myRequest.send();
The question is how do we execute it on a page while it's rendering? I mean put that code directly in src tag name?
Also, is there any way to determine mime-type dynamically? In the answer it's hardcoded and they process an image, not audio. Is there a difference?
I wrote the following (without auth):
<audio id= "audioElement" controls="controls" [src]="getAudio()"> Your browser does not support the HTML5 Audio element. </audio>
<script>
function getAudio()
{
var oReq = new XMLHttpRequest();
oReq.open('GET', 'https://upload.wikimedia.org/wikipedia/ru/6/62/Meow.ogg', true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent)
{
var arrayBuffer = oReq.response;
if (arrayBuffer) {
var u8 = new Uint8Array(arrayBuffer);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));
var mimetype="audio/ogg";
document.getElementById("audioElement").src="data:"+mimetype+";base64,"+b64encoded;
oReq.send(null);
}
}
</script>
But it doesn't work.
What's the problem?
Thanks in advance.
Well , it seems the the proper way to implement such behaviour is the following:
<audio id= "audioElement" controls="controls"> Your browser does not support the HTML5 Audio element. </audio>
<script>
window.onload = function()
{
var oReq = new XMLHttpRequest();
oReq.open('GET', 'https://upload.wikimedia.org/wikipedia/ru/6/62/Meow.ogg', true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent)
{
var arrayBuffer = oReq.response;
if (arrayBuffer)
{
var u8 = new Uint8Array(arrayBuffer);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));
var mimetype="audio/ogg"; // or whatever mime type is
document.getElementById("audioElement").src="data:"+mimetype+";base64,"+b64encoded;
}
}
oReq.send(null);
}
</script>
Hopefully, it will work with basic auth too...
Related
In my site video use the blob data, when the video was downloaded, the saved filename is the blob name with .txt(4671addc-3ce0-4eb6-b414-ddf3406b1fe5.txt) extension in Chrome borwser, while in firefox is with .mp4(4671addc-3ce0-4eb6-b414-ddf3406b1fe5.mp4) extension.
How can I specific the download file extension and the filename.
I've tried to set it with below code, but none works.
type="video/mp4"
filename="111.mp4"
download="111.mp4"
Here is the sample code, I use now.
<video
width="300px"
id="video"
type="video/mp4"
filename="111.mp4"
download="111.mp4"
controls=""
src="blob:http://localhost/4671addc-3ce0-4eb6-b414-ddf3406b1fe5">
</video>
using HTML5 download attribute download the Blob URL file
Notice
download attribute only for HTML5 a or area tag ✅
download attribute not exist on HTML5 video tag ❌
download Blob URL image
<section>
<img id="img" />
<a id="img-link" download>...loading</a>
</section>
// ES5
function generatorBlobURL(url, type, dom, link) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function(res) {
var blob = new Blob(
[xhr.response],
{'type' : type},
);
var urlBlob = URL.createObjectURL(blob);
// render `blob` url ✅
dom.src = urlBlob;
// using `a` tag download ✅
link.href = urlBlob;
link.innerText = urlBlob;
link.download = filename;
};
xhr.send();
}
(function() {
var type = 'image/png';
var url = 'https://cdn.xgqfrms.xyz/logo/icon.png';
var dom = document.querySelector('#img');
var link = document.querySelector('#img-link');
var arr = url.split('/');
var filename = arr[arr.length - 1] || 'default-filename';
generatorBlobURL(url, type, dom, link, filename);
})();
download Blob URL video
<section>
<video id="video" controls width="400" height="300">
loading...
</video>
<br>
<a id="video-link" download>...loading</a>
</section>
// ES5
function generatorBlobURL(url, type, dom, link) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function(res) {
var blob = new Blob(
[xhr.response],
{'type' : type},
);
var urlBlob = URL.createObjectURL(blob);
// render `blob` url ✅
dom.src = urlBlob;
// using `a` tag download ✅
link.href = urlBlob;
link.innerText = urlBlob;
link.download = filename;
};
xhr.send();
}
(function() {
var type = 'video/mp4';
var url = 'https://cdn.xgqfrms.xyz/HTML5/Blob/2022-04-07-sh.mp4';
var dom = document.querySelector('#video');
var link = document.querySelector('#video-link');
var arr = url.split('/');
// arr.at(-1);
var filename = arr[arr.length - 1] || 'default-filename';
setTimeout(() => {
generatorBlobURL(url, type, dom, link, filename);
}, 0);
})();
live demo
https://codepen.io/xgqfrms/full/YzYRLwg
screenshots
refs
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attributes
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes
I am trying to display PDF report inside jsp
I have PDFstream available using following code
private void generatePDFReport(OutputStream stream, JasperPrint jasperPrint) throws JRException {
JRPdfExporter jrpdfexporter = new JRPdfExporter();
jrpdfexporter.setExporterInput(new SimpleExporterInput(jasperPrint));
jrpdfexporter.setExporterOutput(new SimpleOutputStreamExporterOutput(stream));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
jrpdfexporter.setConfiguration(configuration);
jrpdfexporter.exportReport();
}
now I am outputstream which is basically PDF Stream which i want to display into jsp, I dont want to set whole response contenttype as application/pdf but i want to embed pdf into part of jsp output
So i convrted pdfstream output into bytearray and trying to display using following
<script language="Javascript">
function loadDoc() {
alert('called loadDoc');
var xhr = new XMLHttpRequest();
alert('called xhr');
xhr.responseType = 'arraybuffer';
alert('called responseType');
alert('called xhr.onload ');
// Create the Blob URL:
var buffer = xhr.response;
var blob = new Blob([<%=byteCharSet%>], {
type: 'application/pdf'
});
var objectURL = URL.createObjectURL(blob);
alert(objectURL);
// Create an iframe to demonstrate it:
var iframe = document.createElement('iframe');
iframe.className = 'sample-iframe';
iframe.src = objectURL;
document.body.appendChild(iframe);
console.log(objectURL);
//xhr.open('GET', 'https://cors-anywhere.herokuapp.com/http://www.xmlpdf.com/manualfiles/hello-world.pdf', true);
//xhr.send();
}
</script>
but when I am trying to execute javascript couldn't understand bytearray output it simply getting failed blob value getting displayed as below in view page source
var blob = new Blob([%PDF-1.4
%����
3 0 obj
<</Filter/FlateDecode/Length 625>>stream
x���M��0#��>��um�'�v�������C
^���V�����Ķ�H����3�?�}� � �q�D3�
q�`�e��˼'��Do?1�(Ξ�h��2s�S(^�����gĈ^�/b��a�r"\"���_���Г�Lw
I used Iframe to solve this issue.
In iframe for src i used another jsp.
out.write("<iframe src= displayPDF.jsp" + " " + "type=application/pdf width=100% height=600px ");
out.write("</iframe>");
following is the displayPDF.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><%
byte[] pdfByteArray = (byte[]) session.getAttribute("PDFbyteArray");
if (pdfByteArray == null)
System.out.println("pdfByteArray is null");
response.setHeader("Content-Disposition", "inline; filename=\"MyFile.pdf\"");
response.setContentType("application/pdf; name=\"MyFile.pdf\"");
ServletOutputStream serv_out = response.getOutputStream();
serv_out.write(pdfByteArray);
serv_out.flush();
serv_out.close();
out.clear();
session.removeAttribute("PDFbyteArray");%>
I'm using: https://pdfobject.com/
To display an embedded pdf file on my web app. However I cannot render a pdf created from a blob.
This is what I've tried:
var arrayBufferView = new Uint8Array(response.Body.data);
var file = new Blob([arrayBufferView], {
type: response.ContentType
});
var url = window.URL.createObjectURL(file)
PDFObject.embed(url, "#my-container");
Gets me this result on html:
<div id="my-container" class="ng-scope pdfobject-container">
<embed class="pdfobject" src="blob:http%3A//localhost%3A4000/869a8d9a-7eaa-48dd-99aa-49bf299114aa" type="application/pdf" style="overflow: auto; width: 100%; height: 100%;" internalinstanceid="88">
</div>
However the embed container displays nothing in my browser. I'm using Chrome 51.0.2704.103 m
Try using <iframe> element, requesting resource as a Blob
html
<div id="my-container" class="ng-scope pdfobject-container">
<iframe src="" type="application/pdf" width="100%" height="100%" style="overflow: auto;">
</iframe>
</div>
javascript
var xhr = new XMLHttpRequest();
// load `document` from `cache`
xhr.open("GET", "/path/to/file.pdf", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
if (this.status === 200) {
// `blob` response
console.log(this.response);
var file = window.URL.createObjectURL(this.response);
document.querySelector("iframe").src = file;
}
};
xhr.send();
plnkr http://plnkr.co/edit/9E5sGfMhUeIWV9yodAUd?p=preview
Just a complement to the answer by using iframe, we need also to use pdfjs viewer on this otherwise it will download.
<div id="my-container" class="PDFObject-container">
<iframe src="/pdfjs/web/viewer.html?file=blob:http://xxx:8098/fsadfsaf" type="application/pdf" width="1000" height="600" style="overflow: auto;">
</iframe>
</div>
The blob is created from binary response creates with Javascript
const url = window.URL.createObjectURL(new Blob([response], { type: 'application/pdf' }));
I do hope PDFObject can do the work without using iframe but as tested, it's not success.
This is what l believe you were looking for.
function previewPdf(billName) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'home/download?pdfBillId=' + billName, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var file = new Blob([this.response], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
var viewer = $('#viewpdf');
PDFObject.embed(fileURL, viewer);
}
};
xhr.send();
}
Instead of using:
var url = window.URL.createObjectURL(file)
Try using:
var url = window.URL.createObjectURL(file, { type: 'application/pdf' })
I am working on an mobile App and have some issues with the jQuery AJAX get method. I want to receive a video from my server, but somehow I can't receive the file in the format I want.
Here is my code (receiving the data as blob and everything):
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'MyServerAddress/testVideos/test.mp4', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (xhr.status === 200) {
var video = document.createElement('video');
video.src = window.URL.createObjectURL(this.response);
video.autoplay = true;
document.body.appendChild(video);
}else{
"CORS failed. Check Internet Connection."
}
};
xhr.send();
But unfortunately this code doesn't run on mobile devices.
The jQuery Ajax:
jQuery.ajaxSetup({
async:false,
dataType:'blob'
});
$.get("MyServerAddress/testVideos/test.mp4",function(d){
var video = document.createElement('video');
video.src = window.URL.createObjectURL(d);
video.autoplay = true;
document.body.appendChild(video);
}).error(function(xhr, ajaxOptions, thrownError){
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
});
When I run the jQuery code I get the following error:
parser error (index):67 No conversion from text to blob"
Because the transmitted data isn't of the type blob.
Is there any possibility to send the data from jQuery directly as blob? If yes, how? And is there a way to make the code above work on mobile devices too?
Thank you very much,
SirSandmann
I am trying to create a google-chrome-extension that will download an mp3 file. I am trying to use HTML5 blobs and an iframe to trigger a download, but it doesn't seem to be working. Here is my code:
var finalURL = "server1.example.com/u25561664/audio/120774.mp3";
var xhr = new XMLHttpRequest();
xhr.open("GET", finalURL, true);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
bb.append(xhr.responseText);
var blob = bb.getBlob("application/octet-stream");
var saveas = document.createElement("iframe");
saveas.style.display = "none";
saveas.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(saveas);
delete xhr;
delete blob;
delete bb;
}
}
xhr.send();
When looked in the console, the blob is created correctly, the settings look right:
size: 15312172
type: "application/octet-stream"
However, when I try the link created by the createObjectURL(),
blob:chrome-extension://dkhkkcnjlmfnnmaobedahgcljonancbe/b6c2e829-c811-4239-bd06-8506a67cab04
I get a blank document and a warning saying
Resource interpreted as Document but
transferred with MIME type
application/octet-stream.
How can get my code to download the file correctly?
The below code worked for me in Google chrome 14.0.835.163:
var finalURL = "http://localhost/Music/123a4.mp3";
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/octet-stream");
//xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.open("GET", finalURL, true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
var res = xhr.response;
if (res){
var byteArray = new Uint8Array(res);
}
bb.append(byteArray.buffer);
var blob = bb.getBlob("application/octet-stream");
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(iframe);
};
xhr.send(null);
I'm not sure, but i think this is your server's trouble. I've just tried your piece of code to download some sample blob of mp3-file and everything went ok. So maybe:
this file doesn't exist on your server
you server outputs wrong mime type for mp3 files