如何将文件的值转移到服务。文件的值是动态的。
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
import { HttpClient, HttpResponse, HttpRequest,
HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { Subscription } from 'rxjs/Subscription';
import { of } from 'rxjs/observable/of';
import { catchError, last, map, tap } from 'rxjs/operators';
import {CommonService} from '../common.service';
@Component({
selector: 'app-material-file-upload',
templateUrl: './material-file-upload.component.html',
styleUrls: ['./material-file-upload.component.css']
})
export class MaterialFileUploadComponent implements OnInit {
/** Link text */
@Input() text = 'Upload';
/** Name used in form which will be sent in HTTP request. */
@Input() param: any;
/** Target URL for file uploading. */
@Input() target = '';
/** File extension that accepted, same as 'accept' of <input type="file" />.
By the default, it's set to 'image/*'. */
@Input() accept = [];
/** Allow you to add handler after its completion. Bubble up response text from remote. */
@Output() complete = new EventEmitter<string>();
public files: Array<FileUploadModel> = [];
/*private files = <FileUploadModel>{};*/
constructor(private _http: HttpClient, private common: CommonService) { }
ngOnInit() {
}
onClick() {
const fileUpload = document.getElementById('fileUpload') as HTMLInputElement;
fileUpload.onchange = () => {
/*for (let index = 0; index < fileUpload.files.length; index++) {*/
const file = fileUpload.files[0];
this.files.push({ data: file, state: 'in',
inProgress: false, progress: 0, canRetry: false, canCancel: true });
// }
this.uploadFiles();
this.common.uploadProgress = this.files;
};
fileUpload.click();
}
cancelFile(file: FileUploadModel) {
file.sub.unsubscribe();
this.removeFileFromArray(file);
}
retryFile(file: FileUploadModel) {
this.uploadFile(file);
file.canRetry = false;
}
private uploadFile(file: FileUploadModel) {
const fd = new FormData();
// console.log('fileeeeee ', file.data);
if (file.data.type === 'image/jpeg' || file.data.type === 'image/jpg' ||
file.data.type === 'image/png' || file.data.type === 'image/gif') {
console.log('imageeeeeeeeeee');
fd.append('image', file.data);
} else {
fd.append('video', file.data);
}
// this.param.map(index =>{
// console.log(index);
// fd.append(this.param.key(index), this.param.value(index));
// });
/*for (var key in this.param) {
fd.append(key, this.param[key]);
}*/
// console.log(fd);
const req = new HttpRequest('POST', this.target, fd, {
reportProgress: true
});
file.inProgress = true;
file.sub = this._http.request(req).pipe(
map(event => {
switch (event.type) {
case HttpEventType.UploadProgress:
file.progress = Math.round(event.loaded * 100 / event.total);
break;
case HttpEventType.Response:
return event;
}
}),
tap(message => { }),
last(),
catchError((error: HttpErrorResponse) => {
file.inProgress = false;
file.canRetry = true;
return of(`${file.data.name} upload failed.`);
})
).subscribe(
(event: any) => {
if (typeof (event) === 'object') {
this.removeFileFromArray(file);
this.complete.emit(event.body);
}
}
);
}
private uploadFiles() {
const fileUpload = document.getElementById('fileUpload') as HTMLInputElement;
fileUpload.value = '';
this.files.forEach(file => {
this.uploadFile(file);
});
}
private removeFileFromArray(file: FileUploadModel) {
const index = this.files.indexOf(file);
if (index > -1) {
this.files.splice(index, 1);
}
}
}
export class FileUploadModel {
data: File;
state: string;
inProgress: boolean;
progress: number;
canRetry: boolean;
canCancel: boolean;
sub?: Subscription;
}
我想将整个div元素转移到另一个组件。我创建了一个用于上传图片的组件,并将其用于另一个组件。但是上传后我无法显示图片。
<button (click)="onClick()">
<img src="assets/images/videoupload.png" alt="">
</button>
<div *ngFor="let file of files">
<mat-progress-spinner [diameter]="28" [color]="'warn'" class="progress" [value]="file.progress"></mat-progress-spinner>
<span id="file-label">
{{file.data.name}}
<a title="Retry" (click)="retryFile(file)" *ngIf="file.canRetry">
<mat-icon>refresh</mat-icon></a>
<a title="Cancel" (click)="cancelFile(file)" *ngIf="file.canCancel">
<mat-icon>cancel</mat-icon></a>
</span>
</div>
<input type="file" id="fileUpload" name="fileUpload" accept="{{accept}}" style="display:none;"/>
我想在特定位置将div孔用于另一个组件。