Last active
October 3, 2018 12:35
-
-
Save kazuma1989/bc6ce70a6f324e4883710b19c6235cde to your computer and use it in GitHub Desktop.
Angular で、アップロード前のファイルをプレビューしつつ、MD5 値も計算する
This file contains 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
import { Component, OnInit } from '@angular/core'; | |
import { ViewChild } from '@angular/core'; | |
import { ElementRef } from '@angular/core'; | |
import { ArrayBuffer } from 'spark-md5'; | |
import { DomSanitizer, SafeUrl } from '@angular/platform-browser'; | |
@Component({ | |
selector: 'app-bar', | |
template: ` | |
<div> | |
<input type="file" (change)="md5Trial()" #fileInput> | |
</div> | |
<img [src]="src" [alt]="hash" [title]="hash"> | |
`, | |
styleUrls: ['./bar.component.css'] | |
}) | |
export class BarComponent implements OnInit { | |
@ViewChild('fileInput') | |
fileInput: ElementRef; | |
src: SafeUrl; | |
hash: string; | |
constructor( | |
private sanitizer: DomSanitizer | |
) { } | |
ngOnInit() { | |
} | |
md5Trial() { | |
const { files } = this.fileInput.nativeElement; | |
Array.prototype.forEach.call(files, (file: File) => { | |
const reader = new FileReader(); | |
// readAsArrayBuffer() で読み込み、spark-md5 というライブラリーの ArrayBuffer.hash() に渡すと、 | |
// md5 my-image.png | |
// というコマンドで計算した MD5 値と同じものが得られる | |
reader.onload = event => { | |
const { result } = event.target as FileReader; | |
this.hash = ArrayBuffer.hash(result); | |
}; | |
reader.readAsArrayBuffer(file); | |
// URL.createObjectURL() で生成した URL は、そのままだと Angular のセキュリティエラーになるが、 | |
// DomSanitizer.bypassSecurityTrustUrl() を通せばエラーが防げる | |
this.src = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(file)); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment