如何使用Angular 2将.xlsx文件发布到web api?

时间:2018-01-30 05:41:23

标签: angular

我要求管理员用户上传.xlsx文件,其中包含与新用户名称,年龄,性别相关的列。

点击上传按钮,我需要将excel文件发布到WEB API并将数据保存到SQL服务器。

我正在使用Angular 2,如果有人有想法,请告诉我。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您需要有一个可注入的文件上传服务,然后只需从组件中调用它。以下是代码:

<强>服务

import {Injectable, Inject} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import { Subject }    from 'rxjs/Subject';
import {Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class FileUploadService {
 fileUpload(url: string, files: File[])
    : Promise<any> {
    progress$: any;
    progressObserver: any;
    progress: 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("FileUpload", files[i], files[i].name);
        }

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

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

<强>组件

constructor(private fileUploadService: FileUploadService) {
}
this.fileUploadService.fileUpload(this.postURL,this.files)
            .then(dcDetailResponse => this.resetForm(dcDetailResponse))
            .catch(error => console.log(error));

然后在API控制器(c#),根据您的需要进行更改:

[HttpPost]
public IHttpActionResult UploadDCDetail()     
 {
    if (HttpContext.Current.Request.Files.Count > 0)
     {
      }
 }

希望它有所帮助!