How do I get file metadata from URL - javascript

How do I get the data type from a file which is fetched from an URL string, e.g:
https://firebasestorage.googleapis.com/v0/b/MyApp.appspot.com/o/alertImgs%2Falert-1521356210850.jpg?alt=media&token=b6ad7e6e-1eb0-4e05-a11d-e59c8f1df365 (just an example)
When I fetch the URL with javascript from firebase firestore I need to know which data type have the file to put it on a video or image tag.
How can I acomplish this?
I'm working with ionic 3 and firebase.

You can parse url and get last part of url as file name from which you can get extension of file and decide.
function getFileNameFromUrl(url) {
var el = document.createElement('a');
el.href = url;
return decodeURIComponent(el.pathname).split("/").pop();
}
console.log(getFileNameFromUrl("https://firebasestorage.googleapis.com/v0/b/MyApp.appspot.com/o/alertImgs%2Falert-1521356210850.jpg?alt=media&token=b6ad7e6e-1eb0-4e05-a11d-e59c8f1df365"));

Related

How to download .js file by JavaScript from an url?

I know this question is asked hundreds of time in this forum, But I'm trying to download a .js file from an url in my Vue 2 application, but it's not working. Here is what I'm trying:
downloadScript() {
ApiService.post(`url`).then((res) => { // axios
try {
// Create a new link
const url = window.URL.createObjectURL(new Blob([res.data.path]));
const anchor = document.createElement("a");
anchor.href = url;.js";
anchor.setAttribute("download", "script.js");
document.body.appendChild(anchor);
anchor.click();
} catch {
//
}
});
},
This downloads a file which consists nothing but the url I've provided to the axios post request.
I'm getting API response like following:
{
"success": true,
"path": "https://something.com/files/iq-return.min.js"
}
I've to donwload the script in a file from the path
new Blob([res.data.path]) creates a Blob (which is sort-of-like-a-file) containing the text in the string you pass it.
Since that text is a URL, the file you download is a text file containing that URL.
If you want to create a Blob containing the JavaScript source code, then you need to get the JS source code. Make an HTTP request to the URL (e.g. with fetch) and put the response body in the Blob.
(Aside: don't append .js to the generated URL with you set href, that modifies the contents of the file!)
This will, of course, require permission from CORS if this is a cross-origin request.
If it isn't a cross-origin request then you can just set the href attribute to res.data.path without leaping through all these hoops.

node.js url of video id

I'm working on new project.
and I'm trying to get the video id from the URL
the URL needs to be "localhost/MyVid/Watch/xSw23PzA"
xSw23PzA - is the id and I don't know how to get that.
I'm using socket.io to send data for the HTML file, and I have no idea how I can get the Video Id.
If you're always using the same schema
var url = "localhost/MyVid/Watch/xSw23PzA";
var videoId = url.split('/').pop();

Javascript - Print Blob Content Returned from API

I'm building a page for my angular2 web application where a user can select customers from a list and print off letters to mail them. These letters were uploaded as PDFs and are stored as varbinary in the database.
In the case of multiple selections, I'm simply appending byte[]'s so the user will print one document containing all of the letters to send to customers.
I'm able to pull the blob successfully from the API and return it with the content type application-pdf but then I don't know what to do with it from there.
Here's my Angular2 Component API Call:
this.printQueueService.getPrintContent(printRequests) //customers to receive letters
.subscribe((data: Blob) => {
var element: HTMLIFrameElement = <HTMLIFrameElement>document.getElementById('printFile');
element.innerText = data + ""; //what do I do with the blob?
element.contentWindow.print();
});
HTML Element:
<iframe id="printFile" style="display:none"></iframe>
I know I can just download the PDF and prompt the user to print using a PDF Viewer, but I'd rather not force users to go through extra steps.
I'd also rather not try to render the PDF in the browser and print because it assumes users have the proper plugins and browsers support it.
What options do I have for printing a blob in the browser?
As per suggestions from Daniel A. White, I solved this issue. I decided not to use an IFrame because these print files could be massive and the print() function includes the page name as footnotes.
Instead, I chose to open the generated PDF in a new tab as follows:
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(data, "PrintedLetters.pdf"); //IE is the worst!!!
}
else {
var fileURL = URL.createObjectURL(data);
var a: HTMLAnchorElement = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
document.body.appendChild(a);
a.click();
}

Download a file from a server with JavaScript / Typescript

I have a problem when I try to download a file stored on a server. I make a call and get a right response in which I have all the information I need, in the headers I have the content type and the file name, and I have the file body in the response body.
What I want to do is to simply make a download process, so I tried to do so, data being the http call response :
// Get headers info
let headers = data.headers
let contentType = headers.get("Content-Type")
let name = headers.get("name")
// Initialize Blob
let blob = new Blob([data.text()], {type: contentType})
// Make the download process
let a = window.document.createElement("a")
a.href = window.URL.createObjectURL(blob)
a.download = name
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
For a text file, it's working as it's an easy format, but for like a picture or a PDF file it makes download a file of the right name and type, but they can't be well read.
Has anyone an idea ? Thanks !
Found a way to do it using the way described below by simulating an tag with href and download parameters :)
how to set a file name using window.open

Upload file to Windows Azure with only the link of the file is provided

How can I upload a file in azure if I only have the URL of the file to upload. In this case, i 'm using Dropbox file chooser which selects file from dropbox and returns its url path.
eq
https://www.dropbox.com/s/o9myet72y19iaan/Getting%20Started.pdf
Now we need the file to be stored in Windows Azure blob. What is the easiest way to do this without downloading the file first.
I'm planning to use a asp.net web api for the uploading of file to azure blob.
At first, I thought it should be quite straight forward as Azure Blob Storage support copying blobs from external URL however I don't think this would work in case of Dropbox files. I just tried it and got an error even though.
The link you mentioned above is not the direct link to the file. It's a link to a page on Dropbox's website from where you can download a file. This is obviously you don't want. Here's an alternate solution which you can try:
Replace www.dropbox.com in your URL with dl.dropboxusercontent.com (based on #smarx's comments below) and use that URL in the following code:
First you would need to append dl=1 to your request URL as query string. So your Dropbox URL would be https://www.dropbox.com/s/o9myet72y19iaan/Getting%20Started.pdf?dl=1. dl query string parameter indicates the file needs to be downloaded.
Next, using HTTPWebRequest try accessing this URL. Dropbox will respond back with another link and 302 status code. This link would be something like https://dl.dropboxusercontent.com/s/o9myet72y19iaan/Getting%20Started.pdf?token_hash=<tokenhash>.
Use this link in the code below to copy file. This would work.
CloudStorageAccount acc = new CloudStorageAccount(new StorageCredentials("account", "key"), false);
var client = acc.CreateCloudBlobClient();
var container = client.GetContainerReference("container-name");
container.CreateIfNotExists();
var blob = container.GetBlockBlobReference("dropbox-file-name");
blob.StartCopyFromBlob(new Uri("dropbox URL with dl.dropboxusercontent.com"));
Console.WriteLine("Copy request accepted");
Console.WriteLine("Now checking for copy state");
bool continueLoop = true;
do
{
blob.FetchAttributes();
var copyState = blob.CopyState;
switch (copyState.Status)
{
case CopyStatus.Pending:
Console.WriteLine("Copy is still pending. Will check status again after 1 second.");
System.Threading.Thread.Sleep(1000);//Copy is still pending...check after 1 second
break;
default:
Console.WriteLine("Terminating process with copy state = " + copyState.Status);
continueLoop = false;
break;
}
}
while (continueLoop);
Console.WriteLine("Press any key to continue.");

Categories