Javascript 用Angular2上传文件

Javascript 用Angular2上传文件,javascript,c#,angular,xmlhttprequest,asp.net-core,Javascript,C#,Angular,Xmlhttprequest,Asp.net Core,我正在学习一个教程,关于如何使用Angular2上传文件。但是,当我尝试将代码实现到我的项目中时,控制台中的结果只是页面html内容,而不是JSON响应,我认为这是通过后端的POST请求(asp.net core)发送的。在“网络”选项卡下,它似乎将帖子发送到了正确的地址,因此我不知道为什么会得到一个html文档而不是回复数据。有人知道为什么吗 upload.html <h2>Upload</h2> <input type="file" (change)="file

我正在学习一个教程,关于如何使用Angular2上传文件。但是,当我尝试将代码实现到我的项目中时,控制台中的结果只是页面html内容,而不是JSON响应,我认为这是通过后端的POST请求(asp.net core)发送的。在“网络”选项卡下,它似乎将帖子发送到了正确的地址,因此我不知道为什么会得到一个html文档而不是回复数据。有人知道为什么吗

upload.html

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

首先,通过创建表单数据,看起来您正在从角度部分正确地进行操作。在asp.net中,在POST请求中正确获取文件时,我遇到了一些类似的问题。所以我解决这个问题的方法是解析请求中的内容

首先创建一个空方法,这很重要,否则您将以404结束。接下来从请求对象读取文件:

[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);
    }
}
这里有一个选择

服务台

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);
});
}
uploadDealDocumentFile(文档:DealDocument,文件:File[]):可观察{
var url=BASE_url+'fileupload/';
返回可观察的。创建(观察者=>{
让formData:formData=new formData(),
xhr:XMLHttpRequest=新的XMLHttpRequest();
for(设i=0;i{
if(xhr.readyState==4){
如果(xhr.status==200){
next(JSON.parse(xhr.response));
observer.complete();
}否则{
观察者错误(xhr响应);
}
}
};
xhr.upload.onprogress=(事件)=>{
//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";
        }
    }
}
公共类FileUploadController:ApicController
{
[HttpPost()]
公共字符串上载文件()
{
字符串sPath=HostingEnvironment.MapPath(“~/UploadDocs/”);
int iUploadedCnt=0;
HttpFileCollection filescolection=HttpContext.Current.Request.Files;
string id=HttpContext.Current.Request.Form[“id”];
对于(int i=0;i 0)
{
如果(!File.Exists(sPath+Path.GetFileName(File.FileName)))
{                        
SaveAs(sPath+Path.GetFileName(file.FileName));
iUploadedCnt=iUploadedCnt+1;
}
}
}
如果(iUploadedCnt>0)
{
返回iUploadedCnt+“文件上传成功”;
}
其他的
{
返回“上传失败”;
}
}
}

祝你好运

嘿,谢谢你的重播。但是,我在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;名称空间测试.Controllers{[Route(“api/[controller]”)公共类SampleDataController:ControllerMaybe您可以从:HttpContext.Current.Request.Files访问它。问题可能是,我使用的是asp.net MVCW,它相当于asp.net core的HttpFileCollection?同样的问题,只是返回http页面文档。对于Node.js,它似乎正在发布到服务器。
Request.Form.Files;
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);
});
}
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";
        }
    }
}