angular 8 + rxjs + ts 文件上传

用户回答回答于 2018-03-022018-03-02 10:40:15

看看我的代码,

输入更改处理程序:

/**
 * @param fileInput
 */
public psdTemplateSelectionHandler (fileInput: any){
    let FileList: FileList = fileInput.target.files;

    for (let i = 0, length = FileList.length; i < length; i++) {
        this.psdTemplates.push(FileList.item(i));
    }

    this.progressBarVisibility = true;
}

提交处理程序:

public async psdTemplateUploadHandler (): Promise {
    let result: any;

    if (!this.psdTemplates.length) {
        return;
    }

    this.isSubmitted = true;

    this.fileUploadService.getObserver()
        .subscribe(progress => {
            this.uploadProgress = progress;
        });

    try {
        result = await this.fileUploadService.upload(this.uploadRoute, this.psdTemplates);
    } catch (error) {
        document.write(error)
    }

    if (!result['images']) {
        return;
    }

    this.saveUploadedTemplatesData(result['images']);
    this.redirectService.redirect(this.redirectRoute);
}

FileUploadService。该服务还存储上传进度$属性

import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';

@Injectable()
export class FileUploadService {
/**
 * @param Observable
 */
private progress$: Observable;

/**
 * @type {number}
 */
private progress: number = 0;

private progressObserver: any;

constructor () {
    this.progress$ = new Observable(observer => {
        this.progressObserver = observer
    });
}

/**
 * @returns {Observable}
 */
public getObserver (): Observable {
    return this.progress$;
}

/**
 * Upload files through XMLHttpRequest
 *
 * @param url
 * @param files
 * @returns {Promise}
 */
public upload (url: string, files: File[]): Promise {
    return new Promise((resolve, reject) => {
        let formData: FormData = new FormData(),
            xhr: XMLHttpRequest = new XMLHttpRequest();

        for (let i = 0; i < files.length; i++) {
            formData.append("uploads[]", files[i], files[i].name);
        }

        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        };

        FileUploadService.setUploadUpdateInterval(500);

        xhr.upload.onprogress = (event) => {
            this.progress = Math.round(event.loaded / event.total * 100);

            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);
}
}
// 上传表格1
  readExcel(e) {//表格导入
    const files = e.target.files;
    // console.log(files);
    if (files.length <= 0) {//如果没有文件名
      return false;
    } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
      this.msg.error(‘sss’);
      // this.msg.error('上传格式不正确,请上传xls或者xlsx格式');
      return false;
    }

    const fileReader = new FileReader();
    fileReader.onload = (ev: any) => {
      try {
        const data = ev.target.result;
        const workbook = XLSX.read(data, {
          type: 'binary'
        });
        const wsname = workbook.SheetNames[0];//取第一张表
        const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
        // console.log(ws);
        const excellist = [];//清空接收数据
        //编辑数据
        for (var i = 0; i < ws.length; i++) {
          excellist.push(ws[i]);
        }
        // 此时得到的是一个内容是对象的数组需要处理
        // console.log(excellist);
        let arr1 = excellist.map(_ => Object.values(_)[0]);
        // console.log(arr1);
        this.XXX = arr1.map(........);
      

      } catch (e) {
        // console.log('出错了')
        return false;
      }
    };
    fileReader.readAsBinaryString(files[0]);
    this.myBlackBoxChange = false;
    // 如果需要後台處理表格數據,就執行如下操作1
    // 如果是發送後台解析,就這樣發送1
    // let url =  BaseUrl.path +'/ZZZ;
    // let myformdataFile = {
    //   file: e.target.files[0]
    // }
    // if (e.target.files[0]) {
    //   this.http.post(url, myformdataFile).subscribe((res: any) => {
    //     if (res.status == 'success') {
    //       console.log(res)
    //     } else {
    //       this.msg.warning(res.message);
    //       return false;
    //     }
    //   });
    // }
    // 如果是發送後台解析,就這樣發送2
    // 如果需要後台處理表格數據,就執行如下操作2
  }
  // 上传表格2

你可能感兴趣的:(angular 8 + rxjs + ts 文件上传)