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.
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.
[lwptoc]
We’ll create a sample for a simple JavaScript application and Angular as well. In Angular application, 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>
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]);
}
}
Inside the reader.onload
, we’ll get Base64 encoded string URL
// Base64 String
console.log(e.target.result);
# 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);
Final onchange
function
After the file is selected by a user, we’ll append the selected <img> inside the <div id=”selected-file”></div> by using the Javascript, in case of an Image(Png, Jpeg or Gif).
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]);
}
}
That’s it the <a/>
tag we are creating above is having the href
value assigned with blog url
.
Angular Application
For an Angular application, we just need to assign the blob url
in the <a> tag
<a class="view-btn-attach" [href]="selectedFileBLOB" target="_blank">View</a>
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;
...
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]);
}
}
}
This will make passes URL as trusted and used by the user to view the blob url in the new tab.
Conclusion
Finally, we’re done with a tutorial on how to convert the selected file into a Blob url, and append the link to open the selected file in a new browser tab.
Leave a Reply