August 31, 2020 Jolly.Exe
In this JavaScript quick tutorial, we’ll learn how to select a file using a File input control to convert it into a Base64 URL, also add a View button to preview the selected file by opening in the new Chrome tab by creating a BLOB url.
Article compatible with Angular version starting 4+ up to latest version including 6,7,8,9,10,11 and 12.
In the HTML forms, where we have upload document or image functionality, we usually convert the selected file into a Base64 encoded url to upload it as a string to the remote server, where the base64 string is converted into a file and saved on remote disk space.
We have already discussed how to convert the selected file into a Base64 string URL here, you can check the complete tutorial in Angular.
While filling and selecting the files into form, we may need to provide a preview link using which we can display the selected file to the user in a new browser tab. This can be easily done on the Client-end by converting the File into a Blob object URL.
Summary of content
1) What is Blob?
2) Adding a Form
3) Adding JavaScript
3.1) # Create a Blob URL
4) Final onchange function
5) Angular Application
6) Dealing with Unsafe URL’s in Angular
7) Make Unsafe URLs Trusted
8) Conclusion
9) Related Popular Tutorials
We’ll create a sample for a simple JavaScript application and Angular as well. we face unsafe link scenarios which can be resolved by URL sanitization.
What is Blob?
Binary Large Object(Blob) is an Object used to store or holding data in a browser. Blobs can be used to read then save data on disk.
A Blob object has properties to represent the size and MIME type of stored file. This can be used as a normal file.
Adding a Form
Let’s create a simple HTML form with input control of type file
. This file control is having a change event handler to convert the selected file into a base64 string. The onchange
event will take care to convert the file into base64 anf Blog.
<form onsubmit="myFunction(event)">
<label>Select a File</label>
<input type="file" name="myfile" onchange="fileChangeEvent(event)">
<div id="selected-file">
</div>
<button>Upload</button>
</form>
Copy
Copy the code
Adding JavaScript
Now add the fileChangeEvent()
function which will do the main task for fetching the Base64 URL and Blob based URL.
The FileReader()
function is used to read files and then load in the browser’s memory. It returns a callback method onload
inside of which we’ll get selected file information.
function fileChangeEvent(fileInput) { if (fileInput.target.files && fileInput.target.files[0]) { const reader = new FileReader(); reader.onload = (e) => { .... . }; reader.readAsDataURL(fileInput.target.files[0]); } } CopyCopy the code
Inside the reader.onload
, we’ll get Base64 encoded string URL
// Base64 String
console.log(e.target.result);
Copy
Copy the code
Ad by Valueimpression
# Create a Blob URL
To create a Blob we call new Blob()
then call window.URL.createObjectURL()
to convert it into a URL.
// Create a Blog object for selected file & define MIME type
var blob = new Blob(fileInput.target.files, { type: fileInput.target.files[0].type });
// Create Blog URL
var url = window.URL.createObjectURL(blob);
Copy
Copy the code
Final onchange
function
After the file is selected by a user, we’ll append the selected file inside the
function fileChangeEvent(fileInput) {
if (fileInput.target.files && fileInput.target.files[0]) {
const reader = new FileReader();
reader.onload = (e) => {
// Create a Blog object for selected file & define MIME type
var blob = new Blob(fileInput.target.files, { type: fileInput.target.files[0].type });
// Create Blog URL
var url = window.URL.createObjectURL(blob);
var element = document.getElementById("selected-file");
if (
fileInput.target.files[0].type === 'image/png' ||
fileInput.target.files[0].type === 'image/gif' ||
fileInput.target.files[0].type === 'image/jpeg'
) {
// View Image using Base64 String
console.log(e.target.result);
var img = document.createElement("img");
img.src = e.target.result;
element.appendChild(img);
}
// Create Blog View Link
var a = document.createElement("a");
var linkText = document.createTextNode("View File");
a.target = "_blank";
a.appendChild(linkText);
a.href = url;
element.appendChild(a);
};
reader.readAsDataURL(fileInput.target.files[0]);
}
}
Copy
Copy the code
That’s it the tag we are creating above is having the href value assigned with the blog URL.
Angular Application
For an Angular application, we just need to assign the blob url
in the tag
<a class="view-btn-attach" [href]="selectedFileBLOB" target="_blank">View</a>
Copy
Copy the code
But we can’t simply assign the url to the selectedFileBLOB as shown below:
. let blob = new Blob(fileInput.target.files, { type: fileInput.target.files[0].type }); let url = window.URL.createObjectURL(blob); this.selectedFileBLOB = url; . CopyCopy the code
Dealing with Unsafe URL’s in Angular
Now if you see the HTML template, it will show something like this:
Due to security reasons, the non-sanitized dynamic links are automatically marked as Unsafe by Angular.
To resolve this we need to deliberately set them as trusted url by using the DomSanitizer
class.
Make Unsafe URLs Trusted
The bypassSecurityTrustUrl()
method provided by the DomSanitizer
class.
. import { DomSanitizer } from '@angular/platform-browser'; . export class AppComponent implements OnInit { constructor( private sanitizer: DomSanitizer ) {} ngOnInit() { } fileChangeEvent(fileInput: any) { if (fileInput.target.files && fileInput.target.files[0]) { const reader = new FileReader(); reader.onload = (e: any) => { let blob = new Blob(fileInput.target.files, { type: fileInput.target.files[0].type }); let url = window.URL.createObjectURL(blob); this.selectedFileBLOB = this.sanitizer.bypassSecurityTrustUrl(url); }; reader.readAsDataURL(fileInput.target.files[0]); } } } CopyCopy the code
This will make passes URL as trusted and used by the user to view the blob url in the new tab.