angular - 如何使用angular 2上传文件?

标签 angular

我需要使用angular 2上传文件,我在客户端使用它,我在服务器端使用Web Api。我如何使用这个组合来实现

最佳答案

我使用 Angular2 和 ASP.NET Core 成功上传了文件。

我意识到您的后端并不完全相同,但我认为这可能会让您朝着正确的方向前进。

我用了ng2-file-upload from valor-software

使用 npm install 安装它,将它添加到你的包文件夹中,使用 systemjs 或 webpack 配置它。我使用 angular-cli webpack,所以我手动进行的唯一配置是在组件文件中。

前端 Angular2

import { Component, Input } from '@angular/core';
import { NgClass, NgStyle } from '@angular/common';

import {FILE_UPLOAD_DIRECTIVES, FileUploader, Headers} from 'ng2-file-upload/ng2-file-upload';


const URL = 'http://localhost:49513/api/values/';

@Component({
  selector: '...',
  templateUrl: '...',
  providers: [...],
  directives: [FILE_UPLOAD_DIRECTIVES, NgClass, NgStyle]
})

export class ProjectDetailsComponent {

  public myHeaders: Headers[] = [];


  public uploader:FileUploader = new FileUploader(
  {
      url: URL,
      headers: <Headers[]> [
        { name: 'Content-Type', value: 'multipart/form-data' }
      ]
  });

  public hasBaseDropZoneOver:boolean    = false;
  public hasAnotherDropZoneOver:boolean = false;

  ...

  public fileOverBase(e:any):void {
    this.hasBaseDropZoneOver = e;
  }

  public fileOverAnother(e:any):void {
    this.hasAnotherDropZoneOver = e;
  }

  ...
}

后端使用 ASP.NET Core

[HttpPost]
public async Task<ActionResult> Post(IFormFile file)
{
    try
    {
        if (file != null && file.Length > 0)
        {
            var savePath = Path.Combine(_appEnvironment.WebRootPath, "uploads", file.FileName);

            using (var fileStream = new FileStream(savePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }

            return Created(savePath, file)
        }
        return BadRequest();
    }
    catch (Exception)
    {
        return StatusCode(500, ex.Message);
    }

}

奖励:我编辑了他们的 html 以使用 Material2而不是 Bootstrap 。

<div class="container">

      <div class="navbar navbar-default">
          <div class="navbar-header">
              <a class="navbar-brand" href>Angular2 File Upload</a>
          </div>
      </div>

      <div class="row">

          <div class="col-md-3">

              <h3>Select files</h3>

              <div ng2FileDrop
                  [ngClass]="{'nv-file-over': hasBaseDropZoneOver}"
                  (fileOver)="fileOverBase($event)"
                  [uploader]="uploader"
                  class="well my-drop-zone">
                  Base drop zone
              </div>

          </div>

          <div class="col-md-9" style="margin-bottom: 40px">

                <h3>Upload queue</h3>
                <p>Queue length: {{ uploader?.queue?.length }}</p>

                <table class="table">
                    <thead>
                    <tr>
                        <th width="50%">Name</th>
                        <th>Size</th>
                        <th>Progress</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr *ngFor="let item of uploader.queue">


                        <td><strong>{{ item?.file?.name }} {{item?.progress}} %</strong></td>
                        <td nowrap>{{ (item?.file?.size/1024/1024).toFixed(2) }} MB</td>
                        <td>
                            <div class="progress" style="margin-bottom: 0;">

                                <md-progress-bar mode="determinate" value="{{item.progress}}"></md-progress-bar>

                            </div>
                        </td>


                        <td class="text-center">
                            <span *ngIf="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
                            <span *ngIf="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
                            <span *ngIf="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
                        </td>
                        <td nowrap>
                            <button type="button" class="btn btn-success btn-xs"
                                    (click)="item.upload()" [disabled]="item.isReady || item.isUploading || item.isSuccess">
                                <span class="glyphicon glyphicon-upload"></span> Upload
                            </button>
                            <button type="button" class="btn btn-warning btn-xs"
                                    (click)="item.cancel()" [disabled]="!item.isUploading">
                                <span class="glyphicon glyphicon-ban-circle"></span> Cancel
                            </button>
                            <button type="button" class="btn btn-danger btn-xs"
                                    (click)="item.remove()">
                                <span class="glyphicon glyphicon-trash"></span> Remove
                            </button>
                        </td>
                    </tr>
                    </tbody>
                </table>

              <div>
                  <div>
                      Queue progress:
                      <div class="progress" style="">
                          <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': uploader.progress + '%' }"></div>
                      </div>
                  </div>

                  <button (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length" md-raised-button class="md-raised md-primary">Upload all</button>
                  <button (click)="uploader.cancelAll()" [disabled]="!uploader.isUploading" md-raised-button class="md-raised md-warn">Cancel all</button>
                  <button (click)="uploader.clearQueue()" [disabled]="!uploader.queue.length" md-raised-button class="md-accent md-hue-1">Remove all</button>


              </div>
          </div>
      </div>
  </div>

关于angular - 如何使用angular 2上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39226697/

相关文章:

使用真假值的 Angular 单选按钮绑定(bind)

javascript - Angular 2 中的元素更新

Angular Universal 构建因 API 请求而卡在预渲染页面上

angular - 一个应用程序中的多个 ngrx 存储

node.js - 发送短信通知或推送通知的服务

Angular CLI - 为什么 <ng serve> 比 <ng build> 更好?

angular - Angular2+ 中 bootstrap 和 entryComponent 的区别

angular - 为什么 .map 运算符在没有 .pipe 的情况下无法工作(Angular + Angularfire2/auth)?

javascript - 如何替换 Angular 2中的字符串?

angular - 如何在 Angular 中添加带有字符串插值的routerlink