我不知道你是否已經找到了解決辦法,但我無論如何都會發布...
對於這個解決方案不需要任何外部NPM模塊。這裏是一步一步的
運行
$ ionic generate component file-uploader
然後創建新元件複製和粘貼如下
的src /組件/文件的上傳/文件uploader.ts
代碼
import { Component, ViewChild, ElementRef, Input } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
/**
* Usage
*
* <file-uploader [apiUrl]="apiUrl" [params]="uploadParams"></file-uploader>
*
* <file-uploader [apiUrl]="apiUrl" [params]="[{'key':'language_code', 'value': 'en'}]"></file-uploader>
*
*/
@Component({
selector: 'file-uploader',
templateUrl: 'file-uploader.html'
})
export class FileUploaderComponent
{
@ViewChild('file') fileInput: ElementRef;
@Input('apiUrl') apiUrl: string = null;
@Input('params') params: Array<{key: string, value: string}> = [];
@Input('buttonText') buttonText: string = 'Upload';
@Input('buttonType') buttonType: 'button' | 'icon' = 'icon';
@Input('icon') icon: string = 'cloud-upload';
@Input('onUploadSuccess') onUploadSuccess: (file: File, response: any) => void
= function (file: File, response: any) { console.log(file); console.log(response); };
@Input('onUploadError') onUploadError: (file: File) => void = function (error: any) { console.log(error) };
fileToUpload: File = null;
constructor(private httpClient: HttpClient)
{
}
triggerFileInputClick()
{
this.fileInput.nativeElement.click();
}
onFileInputChange(files: FileList)
{
this.fileToUpload = files.item(0);
if (this.fileInput.nativeElement.value != '')
{
this.upload();
}
}
upload()
{
const formData: FormData = new FormData();
formData.append('file', this.fileToUpload, this.fileToUpload.name);
this.params.map(param => {
formData.append(param.key, param.value);
});
let headers = {};
this.httpClient
.post(this.apiUrl, formData, { headers: headers })
// .map(() => { return true; })
.subscribe(response => {
this.onUploadSuccess(this.fileToUpload, response);
this.fileInput.nativeElement.value = '';
}, error => {
this.onUploadError(error);
});
}
}
SRC /組件/文件上傳/文件uploader.html
<div>
<input type="file" #file (change)="onFileInputChange($event.target.files)">
<button *ngIf="buttonType == 'button'" ion-button (click)="triggerFileInputClick()">{{buttonText}}</button>
<ion-icon *ngIf="buttonType == 'icon'" name="cloud-upload" (click)="triggerFileInputClick()"></ion-icon>
</div>
的src /組件/文件的上傳/文件uploader.scss
file-uploader {
[type=file] {
display: none;
}
}
的src /頁/家庭/ home.html的
<file-uploader [apiUrl]="apiUrl" [params]="[{'key':'language_code', 'value': languageCode}]"></file-uploader>
所有你需要的現在要做的就是將組件加載到NgModule中並使用它。
我應該提到的最後一件事是,如果您遇到未定義屬性的問題,例如apiUrl,你應該在ngOnInit()方法中初始化它們。
希望可以幫到