I’ve created a custom HTML component for playing videos. It takes video source as an argument to play the video. How can I play uploaded videos in this component?
I’m using a file uploader to upload the video , the video is coming as a ‘file’ , I don’t quite know how to generate a URL for a file type object.
https://anvil.works/build#clone:ENUQGLIASUO55S4J=K2VXQ6UEPODG42P33BANV2T3
Hello,
If you know a little javascript you could try something like this
document.getElementById("{your file uploader id}").addEventListener("change", (e) => {
var player = document.getElementById("{your HTML video player id}")
let fileBlob = e.target.files[0];
if (fileBlob) {
//clears out previous source
player.src = "";
//adds new source
player.src = URL.createObjectURL(fileBlob);
}
});
Hi,
Since, this is using JavaScript will it go below my file loader function or do I need to define a separate module for it?
Here’s another approach to get the url from a file via a javascript blob object:
def file_loader_1_change(self, file, **event_args):
"""This method is called when a new file is loaded into this FileLoader"""
blob = Blob([file.get_bytes()])
url = URL.createObjectURL(blob)
video_1.src = url
self.file_loader_1.clear()
You may also want to call URL.revokeObjectURL(url)
when you no longer need the URL.
A good time to call the revoke method might be when the video.src
property changes.
@src.setter
def src(self, value):
prev_url = getattr(self, '_src', None)
if prev_url is not None:
URL.revokeObjectURL(prev_url)
self._src = value
self._video.src = value
1 Like
Thanks!!!
The first snippet works like a charm , I don’t understand where I should put the second code snippet.
Take a look at the vide component… that’s where you have the @src.setter
function
edit - another version which also works:
@src.setter
def src(self, value):
self._src = value
self._video.src = value
self._video.play()
URL.revokeObjectURL(value)
2 Likes
Hey,
I’m facing some issues:
Using this:
@src.setter
def src(self, value):
prev_url = getattr(self, '_src', None)
if prev_url is not None:
URL.revokeObjectURL(prev_url)
self._src = value
self._video.src = value
I’m able to upload the video but the video isn’t loading.
When I use this:
@src.setter
def src(self, value):
self._src = value
self._video.src = value
self._video.play()
URL.revokeObjectURL(value)
It’s showing the operation self._video.play() is not supported.
Any ideas?
It looks like some browsers aren’t so great at inferring the content type so adjust the following
def file_loader_1_change(self, file, **event_args):
"""This method is called when a new file is loaded into this FileLoader"""
blob = Blob([file.get_bytes()], {'type', file.content_type})
1 Like