使用Angular2上传文件

时间:2016-09-23 14:53:08

标签: javascript c# angular xmlhttprequest asp.net-core

我正在关注如何使用Angular2上传文件的教程here。但是,当我尝试将代码实现到我的项目中时,我的控制台中的结果只是页面html内容而不是JSON响应,我想通过我的后端(asp.net核心)上的POST请求发送。在网络选项卡下,它似乎使POST到正确的地址,所以我不知道为什么我得到一个HTML文档而不是我的响应数据。谁知道为什么?

upload.html

<h2>Upload</h2>
<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>

upload.ts

import * as ng from '@angular/core';

@ng.Component({
  selector: 'upload',
  template: require('./upload.html')
})
export class Upload {
    filesToUpload: Array<File>;

    constructor() {
        this.filesToUpload = [];
    }

    upload() {
        this.makeFileRequest("http://localhost:5000/api/SampleData/uploadFile", [], this.filesToUpload).then((result) => {
            console.log(result);
        }, (error) => {
            console.error(error);
        });
    }

    fileChangeEvent(fileInput: any){
        this.filesToUpload = <Array<File>> fileInput.target.files;
    }

    makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        return new Promise((resolve, reject) => {
            var formData: any = new FormData();
            var xhr = new XMLHttpRequest();
            for(var i = 0; i < files.length; i++) {
                formData.append("uploads[]", files[i], files[i].name);
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        resolve(JSON.parse(xhr.response));
                    } else {
                        reject(xhr.response);
                    }
                }
            }

SampleData.cs

    [HttpPost]
    public IActionResult uploadFile()
    {
        var files = Request.Form.Files;
        return Json("Working ? ");
    }

2 个答案:

答案 0 :(得分:2)

首先,看起来你是通过创建表单数据从Angular部分做到的。我在asp.net的POST请求中正确获取文件时遇到了类似的问题。所以我解决它的方法是解析Request中的内容。

首先创建一个空方法,这很重要,否则最终会得到404.接下来从Request对象中读取文件:

[HttpPost]
public IActionResult uploadFile()
{
    var files = Request.Files;
    if (Request.Form[0] == null || files[0] == null || files[0].ContentLength < 1)
    {
            // TODO log
            Response.StatusCode = 400;
            return Json("Please provide a file");
    }
    // TODO parse the file(s) as you like :)
    foreach (HttpPostedFile file in files)
    {
        file.SaveAs(file.FileName);
    }
}

[更新为asp.net核心]

更改了asp.net核心中的Request对象,现在表单数据位于:

Request.Form.Files;

答案 1 :(得分:1)

这是一个选项

service.ts

uploadDealDocumentFile(document: DealDocument, files: File[]): Observable<any> {
var url = BASE_URL + 'fileupload/';
return Observable.create(observer => {
  let formData: FormData = new FormData(),
    xhr: XMLHttpRequest = new XMLHttpRequest();

  for (let i = 0; i < files.length; i++) {
    //formData.append("selectedDealId", document.dealId);          
    formData.append("uploads[]", files[i], document.dealCode + '-' + files[i].name);
  }

  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        observer.next(JSON.parse(xhr.response));
        observer.complete();
      } else {
        observer.error(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);
});
}

FileUploadController.cs

public class FileUploadController : ApiController
{
    [HttpPost()]
    public string UploadFiles()
    {
        string sPath = HostingEnvironment.MapPath("~/UploadDocs/");
        int iUploadedCnt = 0;

        HttpFileCollection filesCollection = HttpContext.Current.Request.Files;
        string id = HttpContext.Current.Request.Form["Id"];

        for (int i = 0; i <= filesCollection.Count - 1; i++)
        {
            HttpPostedFile file = filesCollection[i];

            if (file.ContentLength > 0)
            {
                if (!File.Exists(sPath + Path.GetFileName(file.FileName)))
                {                        
                    file.SaveAs(sPath + Path.GetFileName(file.FileName));
                    iUploadedCnt = iUploadedCnt + 1;
                }
            }
        }

        if (iUploadedCnt > 0)
        {
            return iUploadedCnt + " Files Uploaded Successfully";
        }
        else
        {
            return "Upload Failed";
        }
    }
}
祝你好运!!