使用ng2-Uploader上传文件(Angular2)& .net核心

时间:2016-12-14 16:35:05

标签: angular asp.net-web-api file-upload

我需要一些帮助来上传一个带有ng2-uploader库和文件的文件。 Visual Studio 2015上的Web API .net Core,Angular 2&打字稿。

Here are the docs for how to use the ng2-uploader

POST请求没问题,但我的控制器返回_null_

以下是我的文件:

upload.component.ts

import {
    Component
} from '@angular/core';

@Component({
    selector: 'app-upload',
    templateUrl: './app/upload/upload.component.html'
})
export class UploadComponent {
    uploadFile: any;
    hasBaseDropZoneOver: boolean = true;
    options: Object = {
        url: 'http://localhost:65000/customersImport',
    };
    sizeLimit = 2000000;

    handleUpload(data): void {
        if (data && data.response) {
            data = JSON.parse(data.response);
            this.uploadFile = data;
        }
    }

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

    beforeUpload(uploadingFile): void {
        if (uploadingFile.size > this.sizeLimit) {
            uploadingFile.setAbort();
            alert('File is too large');
        }
    }
};

upload.component.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title></title>
</head>

<body>
  <input type="file" ngFileSelect [options]="options" (onUpload)="handleUpload($event)"
    (beforeUpload)="beforeUpload($event)">

  <!-- drag & drop file example-->
  <style>
    .file-over {
      border: dotted 30px red;
    }
    /* Default class applied to drop zones on over */

  </style>
  <div ngFileDrop [options]="options" (onUpload)="handleUpload($event)" [ngClass]="{'file-over': hasBaseDropZoneOver}"
    (onFileOver)="fileOverBase($event)" (beforeUpload)="beforeUpload($event)">
  </div>

  <div>
    Response: {{ uploadFile | json }}
  </div>
</body>

</html>

upload.controller.cs

[Route("[controller]")] 
public class CustomersImportController: Controller 
{
  private readonly IHostingEnvironment _environment;
  public CustomersImportController(IHostingEnvironment environment) 
  {
     _environment = environment;
  }

  [HttpPost] 
  public async Task<ActionResult> UploadCustomers(IFormFile file) 
  {
     var uploads = Path.Combine(_environment.WebRootPath, "uploads");
     try {
           if (file.Length > 0) 
           {
             using(var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create)) 
             {
                await file.CopyToAsync(fileStream);
             }
           }
           return Json("File was Uploaded");
         } 
         catch ()
         { 
             return null;
         }
  }
}

1 个答案:

答案 0 :(得分:2)

如果您使用IFormFile file作为操作的参数,则只能上传一个文件,参数名称(输入名称)必须为“file”。不幸的是我不知道如何使用ng2-uploader设置它。

我想您可以使用数组作为参数来上传多个文件。

我还没有将它用于ng2-uploader,但我会。我会让你联系:)

编辑: 稍微玩一下之后,您可以在上传器的选项中设置字段名称,默认情况下名称为file。 我只按文件上传文件,但它与IFormFile file一起使用,但如果你想上传多个文件,我认为你只需使用IFormFile[] file。当然,如果您想使用IFormFile[] files,请不要忘记更改选项中的名称;)