'Fetching Video(Mp4 format) Using Axios in React and displaying in HTML video

I was trying to fetch a video from backend in the form of byte stream and i was able to get video from backend. But i am unable to handle the video on front end using axios. My code was some thing like

const [video, setVideo] = useState(null);

useEffect(() => {
         axios.get(/pathToVideo, {
                headers: {
                    Accept: 'video/mp4;charset=UTF-8'
                },
            }).then({
        const URL = window.URL || window.webkitURL;
        const url = URL.createObjectURL(new Blob([response.data], {type: "video/mp4"}));
        setVideo(url);
        })
})

and my HTML looks like

            <video controls autoPlay loop muted>
                <source src={video} type="video/mp4"></source>
            </video>

The blob is creating some link but that link contains nothing, can some one suggest me where i am going wrong?



Solution 1:[1]

I don't use React-JS or Axios but from experience with blobs I would try something like this...

  1. Set your HTML first so the axios response code finds the video tag (it has empty .src):
<video id="vidObj" width="500" height="360" controls loop muted autoplay>
<source src="" type="video/mp4">
</video>
  1. Then afterwards you can add your script somewhere as:
    useEffect( () => {
    axios.get( pathToVideo, { headers: { Accept: 'video/mp4;charset=UTF-8' } } )
    .then( response => {
            myUrl = (window.URL || window.webkitURL).createObjectURL( new Blob([response.data]) ); // response.data.data
            
            var myVid = document.getElementById('vidObj');
            myVid.setAttribute("src", myUrl);
            myVid.play(); //# test playback
            
            //setVideo(url); //# is this needed?
        })
    });

The above is untested but hope it helps somehow.

Notes:

  • Does React expect /pathToVideo instead of just pathToVideo?
    (where pathToVideo = "https://somelink.etc";)
  • If response.data does not work, maybe try as response.data.data.
  • I'm not sure what source src={video} does but if possible make .src empty so it's later updated by the axios blob response.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VC.One