繁体   English   中英

使用Angular2上传文件

[英]Upload file with Angular2

我在这里遵循了有关如何使用Angular2上传文件的教程。 但是,当我尝试将代码实现到我的项目中时,控制台中的结果只是页面html内容,而不是JSON响应(我想是通过后端(asp.net core)上的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 ? ");
    }

首先,看起来您是通过创建表单数据从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;

这是一个选择

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

祝好运!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM