I would like to load a file from my storage (Azure) where i don't know the file extension from but i do know the filename, after i would like to use the right file for the src.video. Basically feed every optional video source into videoJS.
this works, but only for two predefined files (mp4/mov):
var video = document.getElementById('my-player')
fileExists()
function fileExists() {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://linktovideo + '.mp4', true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
console.log(xhr.status)
if (xhr.status == 200) {
console.log("MP4 video)
video.src = 'https://linktovideo' + '.mp4';
} else {
console.log("MOV video")
video.src = 'https://linktovideo' + '.mov';
}
}
}
what i like to do is something as this, make a general search for the file (.*);
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://linktovideo + '.*', true);
xhr.send();
xhr.onreadystatechange = processRequest;
then from the actual file extract the extension and glue that to
video.src = 'https://linktovideo' + '.webm';
would something like this be possible? Now of course the XMLrequest returns 404
any ideas or suggestions?
Related
I need to send a HTML-Canvas image from a Webpage to a Servlet for Image Processing. On my webpage, this will be done by uploading a jpg or png image and then clicking a process button.
My frontend is working (I can upload and display images), but I do not know how to send an image from a webpage to a server and vice-versa.
Can you please help me?
HTML: (img stored in canvas)
<canvas id="canvas"></canvas>
JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Ajax Code here???
}
};
xhttp.open("GET", ?, true);
xhttp.send();
Unfortunately, not all browsers does support Canvas.toBlob() function. For example MS Edge and other browsers does not support it (see browser compatibility). Because of this we have to use Canvas.toDataURL() function.
I wrote for you the solution which does the same like normal sending a form from HTML:
var canvas = document.getElementById('canvas'),
dataURL = canvas.toDataURL('image/jpeg', 0.7), //or canvas.toDataURL('image/png');
blob = dataURItoBlob(dataURL),
formData = new FormData(),
xhr = new XMLHttpRequest();
//We append the data to a form such that it will be uploaded as a file:
formData.append('canvasImage', blob);
//'canvasImage' is a form field name like in (see comment below).
xhr.open('POST', 'jsp-file-on-your-server.jsp');
xhr.send(formData);
//This is the same like sending with normal form:
//<form method="post" action="jsp-file-on-your-server.jsp" enctype="multipart/form-data">
// <input type="file" name="canvasImage"/>
//</form>
function dataURItoBlob(dataURI)
{
var aDataURIparts = dataURI.split(','),
binary = atob(aDataURIparts[1]),
mime = aDataURIparts[0].match(/:(.*?);/)[1],
array = [],
n = binary.length,
u8arr = new Uint8Array(n);
while(n--)
u8arr[n] = binary.charCodeAt(n);
return new Blob([u8arr], {type: mime})
}
If you do not know how to save files on server side using JSP, please read:
How to upload files on server folder using JSP
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var canvas = document.getElementById('canvas');
canvas.toBlob(function(blob) {
var oReq = new XMLHttpRequest();
oReq.open("POST", /*URL*/, true);
oReq.onload = function (oEvent) {
// Uploaded.
};
oReq.send(blob);
},'image/jpeg', 0.95);
}
};
xhttp.open("GET", ?, true);
xhttp.send();
More information:CanvasElement toBlob and Sending Blob
Firebase's documentation covers downloading an image if you call storage and getDownloadURL, and I have this working fine (straight from the docs):
storageRef.child('images/stars.jpg').getDownloadURL().then(function(url) {
// `url` is the download URL for 'images/stars.jpg'
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
// Or inserted into an <img> element:
var img = document.getElementById('myimg');
img.src = url;
}).catch(function(error) {
// Handle any errors
});
However, I already have a URL and want to download an image without calling firebase storage. This is my attempt:
var url = "https://firebasestorage.googleapis.com/v0/b/somerandombucketname..."
console.log(url);
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
But, no file is downloaded and no error is shown in the browser's development tools.
Note: I do know the URL is correct because if I put URL directly into my browser search bar, I am able to access the file and download it.
Does anyone know how to download an image using a Download URL that you already have (without calling Firebase Storage as they do in the docs)?
This ended up working for me:
var url = "https://firebasestorage.googleapis.com/v0/b/somerandombucketname..."
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response);
a.download = "fileDownloaded.filetype"; // Name the file anything you'd like.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
};
xhr.open('GET', url);
xhr.send();
This is essentially creating an a href to the URL I have and then clicking the a href programmatically when the xhr response is received.
It is not clear to me why the first way doesn't work as well, but hopefully this helps others that face the same issue.
Thank you for reading!
I want to open a PDF from a REST backend that gets loaded via XHR in a new tab with specified filename and Authorization header.
So far I managed to download it with this (incl. auth headers and filename):
// saves XHR stream as file with configurable filename
downloadXHRFile:function(endpoint,data,method,filename,errorcallback,mimetype){
bsLoadingOverlayService.start();
var def = $q.defer();
var token = localStorageService.get('token');
var xhr = new XMLHttpRequest();
xhr.open(method, CONFIG.URL+endpoint, true);
xhr.setRequestHeader('Authorization', 'Bearer '+token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob=new Blob([this.response], {type:mimetype});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=filename;
link.click();
bsLoadingOverlayService.stop();
}else{
bsLoadingOverlayService.stop();
errorcallback(xhr.statusText);
}
def.resolve();
};
xhr.send(
JSON.stringify(data)
);
return def;
},
Further I managed to open it in a new tab with the following code (incl. auth headers).
Unfortunately the URL (and by that the filename) looks like this:
blob:http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651
Probably it can be solved somehow like above but I cant find the solution.
Does someone have a clever idea how I could set the filename in the new Tab?
// opens XHR filestream in tab
openXHRFile: function(endpoint,filename,errorcallback){
var token = localStorageService.get('token');
var our_url = CONFIG.URL+endpoint;
var win = window.open('_blank');
downloadFile(our_url, function(blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", 'Bearer '+token);
// xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}else{
}
};
xhr.send(null);
}
},
How can I test user credentials using javascript?
I tested the good URL with app_code and app_id. When they are ok all other requests seem to be ok too.
You can do it so e.g.:
var app_id = "test_app_id";
var app_code = "test_app_code";
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4 ) {
if(this.responseText.indexOf("France") != -1){
console.log("Credentials is OK");
}else{console.log("Wrong credentials");}
}
});
xhr.open("GET", "https://geocoder.api.here.com/6.2/geocode.json?app_id="+ app_id+"&app_code=" + app_code + "&country=FRA");
xhr.send();
I have an image in the amazon s3 which has ACL of autherized-users. I'm trying to retrieve that image with GET method. The javascript method (in angular js) looks like this
(In the following example, response contains the necessary data such as authHeader)
var uri = 'https://sample.s3.amazonaws.com/sample/image.jpg';
var postParams = response.data;
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", downloadComplete, false);
xhr.addEventListener("error", downloadFailed, false);
xhr.addEventListener("abort", downloadCanceled, false);
function downloadComplete(e) {
var xhr = e.srcElement || e.target;
if(xhr.status === 200) { //success status
}
else {
}
}
function downloadFailed(e) {
debugger;
}
function downloadCanceled(e) {
debugger;
}
xhr.open('GET', uri, true);
xhr.setRequestHeader('Authorization', postParams.authHeader);
xhr.setRequestHeader('x-amz-content-sha256', postParams.payloadHash);
xhr.setRequestHeader('Host', "sample.s3.amazonaws.com");
xhr.setRequestHeader('x-amz-date', postParams.date);
xhr.send();
But I get a 403 exception which says SignatureDoesNotMatch. Is there anything i'm doing wrong? I'm quite sure that the values i'm providing are correct.
Thanks in advance