Javascript: save image in browser and then use it in markdown

I implement a label editor and accept images with syntax

![any text](http url)

Although I use this syntax, because in my case it is simpler (but the syntax does not really matter, it doesn’t work)

![ID]
...
[ID]: url ("Image title")

This works well when I specify the URL of the image, but what I would do would be to save the image in the browser and display it , and then if the user posts their content, the image should be uploaded .

This seems like the best option to save server space, but I don't know if this is possible.

I tried the base64 image but the url is huge and this causes the parser to crash.

, , , , !

:

fileChange(event: Event) {
  const files = (event.target as HTMLInputElement).files;

  if (!files || !files.length) { return; }

  for (let i = 0; i < files.length; i++) {
    const file = files.item(i);
    const fileType = file.name.split('.').slice(-1).toString();
    if (/* wrong extension */) { continue; }
    if (/* wrong size */) { continue; }
    this.createMediaUrl(file);
  }
}

createMediaUrl(file: File) {

  const media: { file: File, id: string, url: string, name: string } = {} as any;

  const FR = new FileReader();
  FR.onload = () => media.url = FR.result;
  FR.readAsDataURL(file);
  media.name = file.name;
  media.id = Math.random().toString(36).slice(-6);
  media.file = file;
  this.medias.push(media);
  console.log(media);
}

, Typescript, Javascript ( ).

- , : , , , . .

!

+4
1

URL.createObjectURL() . , Base64, , / API-, , , URI blob , , , , :

createMediaUrl(file: File) {
  const media: { file: File, id: string, url: string, name: string } = {} as any;

  media.url = URL.createObjectURL(file);
  media.name = file.name;
  media.id = Math.random().toString(36).slice(-6);
  media.file = file;
  this.medias.push(media);
  console.log(media);
}

.

( @T.J.Crowder )

+2

Source: https://habr.com/ru/post/1695709/


All Articles