Ionic2實戰(zhàn)-圖片上傳功能開發(fā)

前言

本模塊主要實現(xiàn)了通過APP頁面向后端上傳圖片文件的功能,需要前后端配合完成,工作量大概各占了一半吧。

實現(xiàn)思路為首先前端上傳圖片文件流給后臺,后端拿到圖片文件以后直接保存在七牛云存儲上,七牛會生成一個圖片的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文件內(nèi)的uploadImg函數(shù)

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();
      });
  }

最后

這里省略了導(dǎo)入上傳文件工具類fileUpload.service.ts的過程,如果有不清楚的可以去看我GitHub里面的完整項目。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容