【问题标题】:Upload file with Angular2使用 Angular2 上传文件
【发布时间】:2017-02-01 11:47:05
【问题描述】:

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

上传.html

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

上传.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 ? ");
    }

【问题讨论】:

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


    【解决方案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);
    });
    }
    

    文件上传控制器.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";
            }
        }
    }
    

    祝你好运!

    【讨论】:

    • 什么是 HttpFileCollection for asp.net core 的等价物?
    • 同样的问题,只是返回http页面文档。对于 Node.js,它似乎正在发布到服务器。
    【解决方案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 core中的Request对象,现在表单数据在:

    Request.Form.Files;
    

    【讨论】:

    • 嘿,感谢您的重播。但是我在行 var files = Request.Files; .....“HttpRequest”不包含“Files”的定义,并且找不到接受“HttpRequest”类型的第一个参数的扩展方法“Files”(您是否缺少 using 指令或程序集引用?)[ netcoreapp1.0]
    • 你在使用 asp.net 控制器类吗?
    • 是的。使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Threading.Tasks;使用 Microsoft.AspNetCore.Mvc;使用 Microsoft.AspNetCore.Http;命名空间 Testing.Controllers { [Route("api/[controller]")] 公共类 SampleDataController : 控制器
    • 也许你可以从:HttpContext.Current.Request.Files 访问它
    • 哦,也许问题是,我使用的是 asp.net MVC
    猜你喜欢
    • 2017-07-05
    • 1970-01-01
    • 2016-07-21
    • 2017-04-30
    • 2017-06-09
    • 2017-12-04
    • 2017-07-23
    • 2023-03-27
    • 2016-06-29
    相关资源
    最近更新 更多