How To Download Video With Blob Url?
Blobs and object URLs exposed
File downloading is a core aspect of surfing the internet. Tons of files get downloaded from the internet every mean solar day ranging frombinary files (similar applications, images, videos, and audios) to files in obviously text.
Fetching files from the server
Traditionally, the file to be downloaded is first requested from aserver through aclient — such as a user's web browser. The server so returns a response containing thecontent of the file and some instructional headers specifying how the client should download the file.
In this diagram, the light-green line shows the flow of the request from the customer to the server over HTTP. The orange line shows the flow of the response from the server back to the client.
Though the diagram indicates the communication period, it does non explicitly bear witness what the request from the client looks similar or what the response from the server looks similar.
Here is what the response from the server could possibly look like:
In this response, the server but serves the raw content of the resources (represented with the asterisks —*) which volition be received by the client.
The response also contains some headers that give the client some information about the nature of the content it receives — in this example response, theContent-Type andContent-Length headers provide that information.
When the client (web browser in this instance) receives this HTTP response, it but displays or renders the GIF image — which is not the desired beliefs.The desired beliefs is that the image should be downloaded not displayed.
Enforcing file download
To inform the client that the content of the resource is non meant to exist displayed, the server must include an boosted header in the response. TheContent-Disposition header is the correct header for specifying this kind of information.
The Content-Disposition header was originally intended for mail user-agents — since emails are multipart documents that may contain several file attachments. Nonetheless, it tin can exist interpreted by several HTTP clients including spider web browsers. This header provides information on thedisposition type anddisposition parameters.
Thedisposition type is usually one of the following:
- inline — The body part is intended to be displayed automatically when the message content is displayed
- attachment — The body part is separate from the main content of the bulletin and should non be displayed automatically except when prompted by the user
Thedisposition parameters are additional parameters that specify information most the trunk part or file such as filename, creation date, modification date, read date, size, etc.
Here is what the HTTP response for the GIF image should look like to enforce file download:
Now the server enforces a download of the GIF image. Most HTTP clients will prompt the user to download the resource content when they receive a response from a server like the i above.
Click to download in the browser
Let's say you have the URL to a downloadable resources. When you try accessing that URL on your web browser, it prompts yous to download the resource file — whatever the file is.
The scenario described above is not viable in web applications. For spider web applications, the desired beliefs will be —downloading a file in response to a user interaction. For example,click to save a photo ordownload a written report.
Achieving such a behavior in the browser is possible with HTMLballast elements (<a></a>). Anchor elements are useful for adding hyperlinks to other resources and documents from an HTML document. The URL of the linked resource is specified in the href attribute of the anchor element.
Hither is a conventional HTML anchor element linking to a PDF document:
The download attribute
In HTML v, a new download attribute was added to the anchor element. Thedownload aspect is used to inform the browser to download the URL instead of navigating to it — hence a prompt shows upwards, requesting that the user saves the file.
Thedownload attribute can exist given a valid filename as its value. Withal, the user can nonetheless modify the filename in the save prompt that pops-up.
There are afew noteworthy facts near the behavior of the download attribute:
- In compliance with thesame-origin policy, this attribute only works for same-origin URLs. Hence, it cannot exist used to download resources served from a different origin
- Likewise HTTP(southward) URLs, it too supports
blob:anddata:URLs — which makes it very useful for downloading content generated programmatically with JavaScript - For URLs with a HTTP
Content-Dispositionheader that specifies a filename — the header filename has a higher priority than the value of thedownloadattribute
Here is the updated HTML anchor chemical element for downloading the PDF document:
Programmatic content generation
With the appearance of HTML5 and new Web APIs, it has become possible to practice a lot of complex stuff in the browser using JavaScript without ever having to communicate with a server.
At that place are now Web APIs that can be used to programmatically:
- depict and manipulate images or video frames on a sail —Sheet API
- read the contents and properties of files or fifty-fifty generate new information for files —File API
- generate object URLs for binary data —URL API
to mention merely a few.
In this section, nosotros will examine how nosotros can programmatically generate content using Spider web APIs on the browser.
Permit'south consider two common examples .
Example 1 — CSV generation from JSON array
In this example, nosotros will utilize theFetch API to asynchronously fetch JSON information from a web service and transform the data to class a string ofcomma-separated-values that can be written to a CSV file. Here is a breakdown of what we are about to do:
- fetch an assortment drove of JSON objects from an API
- extract selected fields from each item in the array
- reformat the extracted data as CSV
Hither is what the CSV generation script could expect like:
office squareImages({ width = 1, meridian = width } = {}) { render width / top === 1; } function collectionToCSV(keys = []) { render (collection = []) => { const headers = keys.map(key => `"${key}"`).join(','); const extractKeyValues = record => keys.map(cardinal => `"${record[key]}"`).join(','); return collection.reduce((csv, record) => { return (`${csv}\northward${extractKeyValues(tape)}`).trim(); }, headers); } } const exportFields = [ 'id', 'writer', 'filename', 'format', 'width', 'height' ]; fetch('https://picsum.photos/list') .so(response => response.json()) .and so(data => data.filter(squareImages)) .so(collectionToCSV(exportFields)) .then(console.log, console.mistake); Hither nosotros are fetching a collection of photos from the Picsum Photos API using the globalfetch() function provided past theFetch API, filtering the collection and converting the collection array to a CSV cord. The code snippet only logs the resulting CSV cord to the console.
Get-go, we define a squareImages filter function for filtering images in the collection with equal width and height.
Side by side, nosotros define a collectionToCSV higher-order function which takes an array of keys and returns a role that takes an assortment collection of objects and converts information technology to a CSV string extracting merely the specified keys from each object.
Finally, we specify the fields we want to extract from each photo object in the collection in the exportFields array.
Here is what the output could look like on the console:
Case 2 — Paradigm pixel manipulation using the Canvas API
In this example, we will use theCanvas API to manipulate the pixels of an prototype, making information technology appear grayscale. Here is a breakdown of what we are nigh to do:
- set the canvas dimensions based on the image
- depict the image on a sheet
- extract and transform the image pixels on the canvas to grayscale
- redraw the grayscale pixels on the canvas
Allow's say we have a markup that looks pretty much like this:
<div id="epitome-wrapper">
<sheet></canvas>
<img src="https://example.com/imgs/random.jpg” alt="Random Image">
</div>
Here is what the paradigm manipulation script could expect similar:
const wrapper = document.getElementById('image-wrapper'); const img = wrapper.querySelector('img'); const canvass = wrapper.querySelector('canvas'); img.addEventListener('load', () => { sheet.width = img.width; canvass.summit = img.acme; const ctx = canvas.getContext('second'); ctx.drawImage(img, 0, 0, width, tiptop); const imageData = ctx.getImageData(0, 0, width, peak); const data = imageData.information; for (let i = 0, len = information.length; i < len; i += 4) { const avg = (data[i] + data[i + 1] + data[i + 2]) / 3; data[i] = avg; // red data[i + 1] = avg; // dark-green data[i + 2] = avg; // bluish } ctx.putImageData(imageData, 0, 0); }, false); Here is a comparison between an actual prototype and the corresponding grayscale canvas image.
Blobs and object URLs
Earlier nosotros continue to learn how we can download content generated programmatically in the browser, let's take some time to look at a special kind of object interface called Blob , which is already been implemented by nearly of the major spider web browsers. You lot tin can learn about Blobs here.
Blobs are objects that are used to represent raw immutable information. Blob objects store information about the type and size of data they incorporate, making them very useful for storing and working file contents on the browser. In fact, theFile object is a special extension of theBlob interface.
Obtaining blobs
Blob objects tin exist obtained from a couple of sources:
- Created from not-blob data using the
Blobconstructor - Sliced from an already existing blob object using the
Blob.slice()method - Generated from Fetch API responses or other Web API interfaces
Hither are some lawmaking samples for the aforementioned blob object sources:
const data = { name: 'Glad Chinda', country: 'Nigeria', role: 'Spider web Developer' }; // SOURCE 1: // Creating a blob object from not-blob information using the Hulk constructor const hulk = new Blob([ JSON.stringify(data) ], { type: 'awarding/json' }); const paragraphs = [ 'Commencement paragraph.\r\n', '2d paragraph.\r\n', '3rd paragraph.' ]; const hulk = new Blob(paragraphs, { type: 'text/plain' }); // SOURCE ii: // Creating a new hulk past slicing part of an already existing hulk object const slicedBlob = blob.slice(0, 100); // SOURCE 3: // Generating a hulk object from a Spider web API similar the Fetch API // Detect that Response.blob() returns a promise that is fulfilled with a hulk object fetch('https://picsum.photos/id/6/100') .so(response => response.blob()) .then(hulk => { // use blob hither... }); Reading blob content
It is one affair to obtain a blob object and another thing birthday to piece of work with it. I thing yous want to exist able to do is to read the content of the blob. That sounds like a good opportunity to use a FileReader object. Yous can learn virtuallyFileReader objects here.
AFileReader object provides some very helpful methods for asynchronously reading the content of blob objects or files in dissimilar means. TheFileReaderinterface has pretty adept browser back up and supports reading blob data every bit follows(as at the fourth dimension of this writing):
- equally text —
FileReader.readAsText() - as binary string —
FileReader.readAsBinaryString() - equally base64 data URL —
FileReader.readAsDataURL() - as array buffer—
FileReader.readAsArrayBuffer()
Building on the Fetch API instance we had earlier, nosotros can apply aFileReaderobject to read the blob as follows:
fetch('https://picsum.photos/id/six/240') .so(response => response.hulk()) .then(blob => { // Create a new FileReader innstance const reader = new FileReader; // Add a listener to handle successful reading of the blob reader.addEventListener('load', () => { const image = new Epitome; // Set the src attribute of the image to be the resulting data URL // obtained after reading the content of the hulk image.src = reader.result; document.body.appendChild(paradigm); }); // Start reading the content of the blob // The result should be a base64 data URL reader.readAsDataURL(blob); }); Object URLs
TheURL interface allows for creating special kinds of URLs calledobject URLs, which are used for representing blob objects or files in a very curtailed format. Here is what a typical object URL looks like:
hulk:https://cdpn.io/de82a84f-35e8-499d-88c7-1a4ed64402eb Creating and releasing object URLs
The URL.createObjectURL() static method makes it possible to create an object URL that represents a blob object or file. It takes a blob object as its argument and returns aDOMString which is the URL representing the passed blob object. Hither is what it looks like:
const url = URL.createObjectURL(blob); It is important to note that, this method will always return a new object URL each time it is called, even if information technology is called with the same blob object.
Whenever an object URL is created, it stays around for the lifetime of the document on which information technology was created. Usually, the browser volition release all object URLs when the document is being unloaded. All the same, it is of import that you release object URLs whenever they are no longer needed in order to improve functioning and minimize memory usage.
The URL.revokeObjectURL() static method tin can be used to release an object URL. Information technology takes the object URL to be released every bit its argument. Here is what information technology looks like:
const url = URL.createObjectURL(blob); URL.revokeObjectURL(url);
Using object URLs
Object URLs can exist used wherever a URL tin be supplied programmatically. For instance:
- they can exist used to load files that tin can be displayed or embedded in the browser such as images, videos, audios, PDFs, etc — for example, by setting the
srcbelongings of anPrototypeelement - they can be used equally the
hrefattribute of an<a></a>element, making it possible to download content that was extracted or generated programmatically
Downloading generated content
And so far, nosotros have looked at how nosotros tin can download files that are served from a server and sent to the client over HTTP — which is pretty much thetraditional flow. We take also seen how we can programmatically extract or generate content in the browser using Web APIs.
In this section, we will examine how we can download programmatically generate content in the browser, leveraging all we have learned from the beginning of the article and what nosotros already know about blobs and object URLs.
Creating the download link
Start, allow'due south say we have ahulk object past some means. Nosotros want to create a helper role that allows u.s. to create a download link (<a></a> element) that tin can exist clicked in social club to download the content of the blob, simply like a regular file download.
The logic of our helper function tin can be broken down every bit follows:
- Create an object URL for the blob object
- Create ananchor chemical element (
<a></a>) - Set the
hrefattribute of the anchor element to the created object URL - Set the
downloadaspect to the filename of the file to be downloaded. This forces the anchor chemical element to trigger a file download when information technology is clicked - If the link is for a one-off download, release the object URL after the anchor element has been clicked
Here is what an implementation of this helper role will look like:
function downloadBlob(blob, filename) { // Create an object URL for the hulk object const url = URL.createObjectURL(blob); // Create a new ballast element const a = document.createElement('a'); // Set up the href and download attributes for the anchor chemical element // Yous tin can optionally prepare other attributes similar `championship`, etc // Especially, if the anchor element volition be fastened to the DOM a.href = url; a.download = filename || 'download'; // Click handler that releases the object URL after the element has been clicked // This is required for 1-off downloads of the blob content const clickHandler = () => { setTimeout(() => { URL.revokeObjectURL(url); this.removeEventListener('click', clickHandler); }, 150); }; // Add the click event listener on the anchor element // Comment out this line if you don't want a one-off download of the hulk content a.addEventListener('click', clickHandler, faux); // Programmatically trigger a click on the anchor chemical element // Useful if you want the download to happen automatically // Without attaching the anchor chemical element to the DOM // Annotate out this line if you don't want an automated download of the blob content a.click(); // Render the anchor element // Useful if y'all want a reference to the element // in gild to adhere information technology to the DOM or use information technology in some other way return a; } That was a pretty straightforward implementation of the download link helper function. Notice that the helper triggers ai-off automatic download of the blob content whenever it is called.
Also notice that the helper function takes a filename as its second statement, which is very useful for setting the default filename for the downloaded file.
The helper function returns a reference to the created ballast element (<a></a>), which is very useful if you desire to adhere it to the DOM or utilize it in another way.
Here is a unproblematic example:
// Blob object for the content to be download const blob = new Hulk( [ /* CSV string content here */ ], { type: 'text/csv' } ); // Create a download link for the hulk content const downloadLink = downloadBlob(blob, 'records.csv'); // Set up the title and classnames of the link downloadLink.title = 'Export Records as CSV'; downloadLink.classList.add together('btn-link', 'download-link'); // Set the text content of the download link downloadLink.textContent = 'Export Records'; // Adhere the link to the DOM document.body.appendChild(downloadLink); Revisiting the examples
Now that we have our download helper function in place, we can revisit our previous examples and modify them to trigger a download for the generated content. Here we go.
1. CSV generation from JSON array
We will update the terminal promise.then handler to create a download link for the generated CSV string and automatically click it to trigger a file download using thedownloadBlob helper part nosotros created in the previous department.
Here is what the modification should expect like:
fetch('https://picsum.photos/list') .then(response => response.json()) .and then(data => data.filter(squareImages)) .then(collectionToCSV(exportFields)) .then(csv => { const blob = new Hulk([csv], { blazon: 'text/csv' }); downloadBlob(blob, 'photos.csv'); }) .catch(console.error); Here we have updated the last promise .and then handler as follows:
- create a new blob object for the CSV string, as well setting the right type using:
{ type: 'text/csv' } - phone call the
downloadBlobhelper function to trigger an automated download for the CSV file, specifying the default filename every bit"photos.csv" - motility the promise rejection handler to a separate
.catch()block:
.catch(console.error) Hither is a working and more advanced instance of this awarding on Codepen :
Encounter the Pen
JSON Collection to CSV past Glad Chinda (@gladchinda)
on CodePen.
two. Prototype pixel manipulation
We will add some lawmaking to the stop of theload event listener of theimgobject, to allow us:
- create a blob object for the grayscale image in the
canvasusing theSheet.toBlob()method - and then create a download link for the blob object using our
downloadBlobhelper function from before - and finally, suspend the download link to the DOM
Here is what the update should look similar:
img.addEventListener('load', () => { /* ... some code have been truncated hither ... */ ctx.putImageData(imageData, 0, 0); // Sheet.toBlob() creates a hulk object representing the image contained in the canvas // It takes a callback function every bit its argument whose outset parameter is the canvas.toBlob(hulk => { // Create a download link for the blob object // containing the grayscale image const downloadLink = downloadBlob(blob); // Set the championship and classnames of the link downloadLink.title = 'Download Grayscale Photo'; downloadLink.classList.add('btn-link', 'download-link'); // Ready the visible text content of the download link downloadLink.textContent = 'Download Grayscale'; // Attach the link to the DOM certificate.body.appendChild(downloadLink); }); }, false); Here is a working example of this application onCodepen :
See the Pen
Image Pixel Manipulation — Grayscale by Glad Chinda (@gladchinda)
on CodePen.
Decision
Nosotros've finally come to the end of this tutorial. While there could be a lot to pick from this tutorial, it is glaring that Spider web APIs have a lot to offering equally regards building powerful apps for the browser. Don't hesitate to exist experimental and adventurous.
Cheers for making out time to read this article. If y'all found this article insightful, feel free to give some rounds of applause if you don't mind — as that will assist other people observe it easily on Medium.
Source: https://blog.logrocket.com/programmatic-file-downloads-in-the-browser-9a5186298d5c/
Posted by: morganthorm1943.blogspot.com

0 Response to "How To Download Video With Blob Url?"
Post a Comment