Ionic2实战-图片上传功能开发
2018-03-29 本文已影响326人
逃离火星
前言
本模块主要实现了通过APP页面向后端上传图片文件的功能,需要前后端配合完成,工作量大概各占了一半吧。
实现思路为首先前端上传图片文件流给后台,后端拿到图片文件以后直接保存在七牛云存储上,七牛会生成一个图片的url,后端将此url返回给前端,前端在提交整个表单的时候带着该url,url即代表该文件。
步骤
1、定义文件上传工具类fileUpload.service.ts
import {Injectable} from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {Helper} from "./helper.service";
@Injectable()
export class FileUploadService {
/**
* @param Observable<number>
*/
private progress$: Observable<any>;
/**
* @type {number}
*/
private progress: number = 0;
private progressObserver: any;
imageUploadAPI: string = this.helper.getAPP('imageUtil/uploadImage');
constructor (private helper: Helper) {
this.progress$ = new Observable(observer => {
this.progressObserver = observer
});
}
/**
* @returns {Observable<number>}
*/
public getObserver (): Observable<number> {
return this.progress$;
}
/**
* Upload files through XMLHttpRequest
*
* @param url
* @param files
* @returns {Promise<T>}
*/
public upload (url: string, files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("file", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(xhr.response);
}
}
};
FileUploadService.setUploadUpdateInterval(500);
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
if (this.progressObserver) {
this.progressObserver.next(this.progress);
}
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
/**
* Set interval for frequency with which Observable inside Promise will share data with subscribers.
*
* @param interval
*/
private static setUploadUpdateInterval (interval: number): void {
setInterval(() => {}, interval);
}
}
2、需要上传文件的页面添加input file代码
<button ion-button outline item-end icon-left>
选择图片
<input class="input-img" #inputReportImg type="file" (change)="uploadImg($event)" accept="image/*">
</button>
3、ts文件内的uploadImg函数
uploadImg(event) {
let files = event.srcElement.files;
this.heyApp.fileUploadService.upload(this.heyApp.fileUploadService.imageUploadAPI, files)
.then(data => {
this.factory.factoryImage = data;
this.heyApp.utilityComp.dismissLoading();
}, () => {
this.heyApp.utilityComp.dismissLoading();
});
}
最后
这里省略了导入上传文件工具类fileUpload.service.ts的过程,如果有不清楚的可以去看我GitHub里面的完整项目。