Skip to content

Instantly share code, notes, and snippets.

@zmnv
Last active February 25, 2022 19:40
Show Gist options
  • Save zmnv/3049447ef7dd2802fa6148c4b1215896 to your computer and use it in GitHub Desktop.
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)
/* 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);
}
}
}
@zmnv
Copy link
Author

zmnv commented Mar 1, 2019

base64 можно сохранять в поле базы данных, т.е. не хранить картинки в виде файлов, а хранить их в бд, типа монги или sqlite т.д.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment