0

I am using this code to get my hands on an image that was just "uploaded" into browser using <input type="file"> and sending data to some component that uses it.

 fileReady(e) {
    let file: File = e[0];
    let image = new Image();
    let src: string;

    image.onload = function () {
      src = image.src;
      //do something with image

    }.bind(this);
    src = URL.createObjectURL(file);
    image.src = src;
  }

This work well for images. Next goal, is to make it work with videos too. There is unfortunately no Video() constructor and HTMLVideoElement also doesn't do the trick. How should I rewrite this code so that it can handle videos?

2
  • you can use Blob type Commented Nov 20, 2017 at 18:32
  • Could you share an example? Commented Nov 20, 2017 at 19:00

2 Answers 2

3

Like this:

fileReady(e) {
      const file: File = e[0];
      const fileReader = new FileReader();
      fileReader.onloadend = (event: any) => {
        const arrayBuffer = event.target.result;
        const fileType = "video/mpeg";
        const blob = new Blob(arrayBuffer , {type: fileType });
        const src = URL.createObjectURL(blob);
        video.src = src;
      };
      fileReader.readAsArrayBuffer(file);
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you sir! I am getting an error on the line: e.target.result, saying that result does not exist on type EventTarget
@sanjihan i fixed
Thanks. I ended up doing a typecast: const beforeResult = <FileReader>e.target; . And for future readers... Blob takes an array of blob parts, as in const blob = new Blob([arrayBuffer] , {type: fileType });
Hello @ЮраПанарин can you take a look at my question please stackoverflow.com/questions/52978624/…
1

Just to add a latest update in the answer,

const blob = new Blob(arrayBuffer , {type: fileType });

will give error that the Blob needs an iterable. So the fix is :

const blob = new Blob([arrayBuffer], {type: fileType });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.