Ionic 2从浏览器上传文件
问题描述:
我有一个Ionic 2 PWA,所以它应该在浏览器中运行。我希望用户可以将文件上传到服务器。由于离子本机文件选择器仅适用于Android,因此我无法在浏览器中使用它。所以我的想法是使用type =“file”的输入字段。但我的问题是,我只获取文件名而不是路径。要上传文件,我需要路径。起初,我已经尝试过用ngModel,然后用离子型表单生成器。这是我的代码与表单生成器:Ionic 2从浏览器上传文件
TS:
import {Component} from '@angular/core';
import {Validators, FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'page-test',
templateUrl: 'test.html',
})
export class TestPage {
private file : FormGroup;
constructor(private formBuilder: FormBuilder) {
this.file = this.formBuilder.group({
image: ['']
});
}
logForm(){
console.log(this.file.value)
}
}
HTML:
...
<ion-content padding>
<form [formGroup]="file" (ngSubmit)="logForm()">
<input type="file" size="50" formControlName="image">
<button ion-button type="submit">Submit</button>
</form>
</ion-content>
但就像我说的,控制台只记录的文件名:
对象{image:“2970.jpg”}
如果我登录“this.file”(没有.value),我发现没有文件对象或类似的东西。有没有办法让离子浏览器应用程序中的文件路径上传到服务器?
答
我不知道你是否已经找到了解决办法,但我无论如何都会发布...
对于这个解决方案不需要任何外部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()方法中初始化它们。
希望可以帮到