Last active
February 25, 2022 19:40
-
-
Save zmnv/3049447ef7dd2802fa6148c4b1215896 to your computer and use it in GitHub Desktop.
Paste image into DOM as base64 img src="" by ctrl+c ctrl+v clipboard. Angular TS, JS example by (paste)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Click by div'container' or any element inside in browser and ctrl+v to paste image. */ | |
/* Pls copy any image in clipboard before :) */ | |
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; | |
@Component({ | |
selector: 'catalog-page-upload', | |
template: /*html*/` | |
<div class="container" (paste)="onPaste($event)"> | |
<h1>Привет , мир!</h1> | |
<img #imgRenderer /> | |
</div> | |
` | |
}) | |
export class PasteFromClipboardComponent { | |
@ViewChild('imgRenderer') imgRenderer: ElementRef; | |
onPaste(event: any) { | |
const items = event.clipboardData.items; | |
let blob = null; | |
for (const item of items) { | |
if (item.type.indexOf('image') === 0) { | |
blob = item.getAsFile(); | |
} | |
} | |
// load image if there is a pasted image | |
if (blob !== null) { | |
const fileFromBlob: File = new File([blob], 'your-filename.jpg'); | |
const reader = new FileReader(); | |
reader.onload = (evt: any) => { | |
console.log(evt.target.result); // data url! | |
this.imgRenderer.nativeElement.src = evt.target.result; | |
}; | |
reader.readAsDataURL(blob); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
base64 можно сохранять в поле базы данных, т.е. не хранить картинки в виде файлов, а хранить их в бд, типа монги или sqlite т.д.