【问题标题】:Having trouble uploading image from Angular 8 to ASP.Netcore Web API无法将图像从 Angular 8 上传到 ASP.Net Core Web API
【发布时间】:2019-08-25 19:53:09
【问题描述】:

我花了一整天的时间试图让它工作,我查看了以下内容:

还有很多,我数不过来。

我只想发送一张表格和一张图片。得到的错误是:

  • 缺少内容类型边界

  • 内容类型不正确

  • 函数求值需要所有线程运行

角度

register(user: UserViewModel, logo: File) {
    // We use formData because we can't send file as an object
    const formData = new FormData();

    formData.append("user", JSON.stringify(user));

    formData.append("logo", logo);

    console.log(formData);

    return this.http.post<UserRegisterViewModel>(`${UserAPI.API_User}/${"register"}`, formData).pipe(map(user => {

      return user;

    }));
  }

比我的 c# 代码看起来像这样

[HttpPost, DisableRequestSizeLimit]
        [AllowAnonymous]
        [Route("register")]
        //[Consumes("application/json", "multipart/form-data")]
        public async Task<IActionResult> RegisterAsync()
        {

            IFormFile logo = null;

            try
            {

                // Get the logo
                logo = Request.Form.Files[0];
                // Get the user json string
                var userJson = Request.Form["user"];

【问题讨论】:

  • 为什么人们不赞成这个,如果你有解决方案,我已经尝试过其他人,但他们不起作用

标签: c# angular asp.net-core


【解决方案1】:

如果你想从Request.Form 获取文件。你可以按照下面的代码示例:

客户端:

const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);

this.http.post('https://localhost:5001/api/upload', formData, {reportProgress: true, observe: 'events'})
.subscribe(event => {
    if (event.type === HttpEventType.UploadProgress)
    this.progress = Math.round(100 * event.loaded / event.total);
    else if (event.type === HttpEventType.Response) {
    this.message = 'Upload success.';
    this.onUploadFinished.emit(event.body);
    }
});

服务器端:

[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload()
{
    try
    {
        var file = Request.Form.Files[0];
        var folderName = Path.Combine("StaticFiles", "Images");
        var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

       .....
    }
    catch (Exception ex)
    {
       ....
    }
}

或者您可以使用 FromForm 获取文件:

客户端:

let fileToUpload = <File>files[0];
const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);

this.http.post('YourURL', formData, {headers: {
  'Accept': 'application/json',     
  'Content-Disposition' : 'multipart/form-data'
},reportProgress: true, observe: 'events'})
  .subscribe(event => {
    ....
  });

那么服务器端将是:

[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload([FromForm(Name = "file")] IFormFile file)
{


}

【讨论】:

    【解决方案2】:

    这解决了它,我有一个断点

    logo = Request.Form.Files[0];
    

    由于某种原因,VS2017 和 2019 中存在错误。

    https://developercommunity.visualstudio.com/content/problem/146887/vs2017-v4-requestform-debug.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-03
      • 2019-08-07
      • 2020-04-08
      • 2020-03-15
      • 1970-01-01
      • 2020-10-05
      • 2020-12-22
      • 1970-01-01
      相关资源
      最近更新 更多