#image #angular #typescript
#изображение #angular #машинописный текст
Вопрос:
Я создал приложение Angular2, которое позволяет пользователю загружать изображения. Я хочу реализовать опцию предварительного просмотра. Однако, когда я пытаюсь подвергнуть его опасности, изображение не отображается. Как мне добиться этой функции?
UploadComponent.ts
import * as ng from '@angular/core';
//import { UPLOAD_DIRECTIVES } from 'ng2-uploader';
import {UploadService} from '../services/upload.service';
@ng.Component({
selector: 'my-upload',
providers:[UploadService],
template: require('./upload.html')
})
export class UploadComponent {
progress:any;
logo:any;
filesToUpload: Array<File>;
constructor(public us:UploadService){
this.filesToUpload = [];
}
upload() {
this.us.makeFileRequest("http://localhost:5000/api/SampleData/Upload", this.filesToUpload)
.then((result) => {
console.log(result);
}, (error) => {
console.error(error);
});
}
onFileChange(fileInput: any){
this.logo = fileInput.target.files[0];
}
}
Upload.html
<h2>Upload</h2>
<input type="file" (change)="onFileChange($event)" placeholder="Upload image..." />
<button type="button" (click)="upload()">Upload</button>
<img [src]="logo" alt="Preivew">
Ответ №1:
При том, как вы это делаете, вы получаете не URL-адрес изображения fileInput.target.files[0]
, а объект.
Чтобы получить URL-адрес изображения, вы можете использовать FileReader
(документация здесь)
onFileChange(fileInput: any){
this.logo = fileInput.target.files[0];
let reader = new FileReader();
reader.onload = (e: any) => {
this.logo = e.target.result;
}
reader.readAsDataURL(fileInput.target.files[0]);
}
Комментарии:
1. Да, это объясняет, почему я продолжал видеть FileReader в коде других людей. Спасибо!
2. Могу ли я оставить изменить его на reader.readAsDataURL(this.logo); вместо reader.readAsDataURL(fileInput.target. файлы[0]); ? Или это приведет к ошибке?
Ответ №2:
filesToUpload: Array<File> = [];
url: any;
image: any;
//file change event
filechange(fileInput: any) {
this.filesToUpload = <Array<File>>fileInput.target.files;
this.image = fileInput.target.files[0]['name'];
this.readurl_file(event);
}
//read url of the file
readurl_file(event) {
if (event.target.files amp;amp; event.target.files[0]) {
const reader = new FileReader();
reader.onload = (eve: any) => {
this.url = eve.target.result;
};
reader.readAsDataURL(event.target.files[0]);
}
}
<div class="form-group">
<label for="image">Image</label>
<input type="file" class="form-control" (change)="filechange($event)" placeholder="Upload file..." >
</div>
<div class="container">
<img [src]="url">
</div>
Ответ №3:
Использование FileReader не является хорошей практикой. Если изображение слишком большое, это может привести к сбою вашего браузера, поскольку функция onload загружает все изображение в ОЗУ.
Лучший подход заключается в использовании:
url = URL.createObjectURL($event.target.files[0]);
Затем покажите его с помощью DomSanitizer:
this.sanitizer.bypassSecurityTrustUrl(url)
Итак, в ts:
constructor(private sanitizer: DomSanitizer) {}
onFileChange(fileInput: any){
this.url = URL.createObjectURL($event.target.files[0]);
}
get previewUrl(): SafeUrl {
return this.sanitizer.bypassSecurityTrustUrl(this.url);
}
И в html:
<img [src]="previewUrl"/>