ASP.NET Core 2.0和Angular 4.3文件上传进度 [英] ASP.NET Core 2.0 and Angular 4.3 File Upload with progress

查看:221
本文介绍了ASP.NET Core 2.0和Angular 4.3文件上传进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新的Angular 4.3 HttpClient ,如何上传和在向客户端报告上传进度的同时访问ASP.NET Core 2.0 Controller中的文件?

Using the new Angular 4.3 HttpClient, how can I upload and access files in an ASP.NET Core 2.0 Controller while reporting upload progress to the client?

推荐答案

下面是一个有效的示例开始:

Here is a working example to get started:

<input #file type="file" multiple (change)="upload(file.files)" />
<span *ngIf="uploadProgress > 0 && uploadProgress < 100">
    {{uploadProgress}}%
</span>






TypeScript




TypeScript

import { Component } from '@angular/core';
import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http'

@Component({
    selector: 'files',
    templateUrl: './files.component.html',
})
export class FilesComponent {
    public uploadProgress: number;

    constructor(private http: HttpClient) { }

    upload(files) {
        if (files.length === 0)
            return;

        const formData = new FormData();

        for (let file of files)
            formData.append(file.name, file);

        const req = new HttpRequest('POST', `api/files`, formData, {
            reportProgress: true,
        });

        this.http.request(req).subscribe(event => {
            if (event.type === HttpEventType.UploadProgress)
                this.uploadProgress = Math.round(100 * event.loaded / event.total);
            else if (event instanceof HttpResponse)
                console.log('Files uploaded!');
        });
    }
}






控制器




Controller

[HttpPost, DisableRequestSizeLimit, Route("api/files")]
public async Task UploadFiles()
{
    var files = Request.Form.Files; // now you have them
}

这篇关于ASP.NET Core 2.0和Angular 4.3文件上传进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆