I am trying to upload a video and preview it in the webpage but the video being uploaded is just not playing despite being uploaded correctly.
Here are the steps I am doing :
- Upload a file in UI
- Read the file using readAsDataURL() method of fileReader instance.
- Uploaded file is read and converted to a base64 format string.
- Convert base64 to a binary data
- Create a blob with which contains the file data in converted binary format.
- Create a URL for above created blob.
- Provide this URL as source for my video tag in HTML
Here is the code of my HTML file :
<input type="file" (change)="trigger($event)">
<video width="400" height="400" controls *ngIf="videoSource">
<source [src]="videoSource" type="video/quicktime">
Your browser does not support the video tag.
</video>
Here is the code of TS file in Angular :
trigger(uploadedFileEvent){
const videoPlayer = document.getElementById('videoPlayer');
let fileReader = new FileReader();
if(uploadedFileEvent.target.files[0]) fileReader.readAsDataURL(uploadedFileEvent.target.files[0]);
new Promise( (resolve,reject) => {
fileReader.onload = function(event) {
const source = event.target.result;
resolve (source)
}
}).then(source => {
let videoSource = source as string;
this.videoSource = atob(videoSource.replace(/^[^,]*,/ ,'')); // convert to binary data
let view = new Uint8Array(videoSource.length);
for (let i = 0; i < videoSource.length; i++) {
view[i] = videoSource.charCodeAt(i);
}
const videoBlob = new Blob([view] , {type : 'video/quicktime'});
this.videoSource = URL.createObjectURL(videoBlob);
})
}
I have checked around in all places. The approach seems to be correct but I don’t seem to understand why this code is failing.
Please let me know how I can make this solution work. In case there is any alternative solution anybody is aware of please post them. In case anybody finds this questions as repetitive I apologise but I was unable to solve despite checking online resources.
Thanks for the help!