skip to Main Content

I’ve got a video stored locally on my computer in a folder called assets. I’m importing the file currently like this into my project:

import sample1 from './assets/sample1.mp4';

I want to use the file as a File() or Blob() object, however I do not know how I could convert the string path Webpack is giving me to one of those objects.

I am using React with create-react-app, so changing the Webpack configuration would not be ideal.

I thought the FileReader() object would solve my problem, however it only accepts Blob() objects.

2

Answers


  1. Chosen as BEST ANSWER

    I'm not using an ideal solution, however this works and the Webpack configuration does not need to be changed.

    @somethingthere's solution would work, if the file would be directly imported as a base64 encoded string, however the Webpack configuration from create-react-app handles this differently and only the file path is contained in the imported variable. But I hadn't come to this solution without her/him.

    1. I've converted my assets to base64 strings with this tool and downloaded the strings as text files.
    2. Opening the files crashed the "Text Editor" application on my Ubuntu machine, so I've copied the files to my clipboard with the following command: cat base64.txt | xclip -selection clipboard.
    3. Then I converted the output to a data URL, just write the following text in front of your base64 string and make sure to change the data-type: data:video/mp4;base64,YOURSTRING.
    4. For each asset I created a JavaScript file with a default export, which exports the created string.
    5. Now you can import the data-url string and convert it to a Blob() as follows:
    async function convertToBlob() {
      const res = await fetch(MYIMPORT);
      const blob = await MYIMPORT.blob();
    }
    

    Done!


  2. You can convert it to a blob using the Blob constructor as such:

    const blob = new Blob([ value1 ], { type: 'video/mp4' });
    

    The first argument is an array of chunks (of which you have 1, so one entry), the second is some metadata. By setting the type there it should read the data correctly. You can find out more at the docs about Blob: https://developer.mozilla.org/en-US/docs/Web/API/Blob

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search