【问题标题】:angular http post for image file to api return code 401将图像文件的角度 http 发布到 api 返回代码 401
【发布时间】:2019-11-28 18:51:35
【问题描述】:

这是我的角码

let fileToUpload = this.profilePhotoFiles[0];
      let formData: FormData = new FormData();
      formData.append('file', fileToUpload, fileToUpload.name);

      this._http.post('/api/Media/upload', formData , {
        headers: {
          'Accept': 'application/json',
          'Content-Type': fileToUpload.type,
          'Content-Disposition' : 'multipart/form-data'
        }
      })
        .subscribe(r => console.log(r));

这就是我的 api 实现方式,

        [HttpPost]
        [Route("upload")]
        public IActionResult UpdatePicture([FromForm(Name = "file")] IFormFile file)
        {
            if (file == null)
                return StatusCode(500);
            //...............myUploadingCode
            return Ok();
        }

网址和身份验证都很好且正确。但它返回代码 401 并且无法访问 API 方法 UpdatePicture
我该如何解决?我在这里错过了什么?

编辑

这就是我获取上传照片的formData的方式

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

更新 1

Authorization 标头之后

        this.headers = this.headers.append('Authorization', myTokenValue);

它通过了401 unauthorize,但它返回了 415 种不受支持的格式。

更新 2

在我添加之后

        this.headers = this.headers.set('Content-Disposition', 'multipart/form-data');

它通过代码415但在API控制器中,但参数IFormFile file为空。

来自this问题的参考。

【问题讨论】:

  • 当您使用 postman 尝试此 API 时发生了什么?
  • 您是否使用 XSRF 保护?它看起来不像你发送的那样,asp.net 总是会从我所看到的返回 401
  • @SudarshanaDayananda ,在邮递员中也是如此。 (401)

标签: angular asp.net-core-webapi


【解决方案1】:

你应该删除Web API中的参数并通过HttpRequest这样获取图像内容

            [HttpPost]
            [Route("upload")]
            public IActionResult UpdatePicture()
            {
                var httpRequest = HttpContext.Current.Request;
                //Upload Image
                var file = httpRequest.Files["file"];
                //Create custom filename
                if (file != null)
                {
                }
                if (file == null)
                    return StatusCode(500);
                //...............myUploadingCode
                return Ok();
            }

也不需要传递你的标题。

this._http.post('/api/Media/upload', formData , {
        headers: {
          'Accept': 'application/json',
          'Content-Type': fileToUpload.type,
          'Content-Disposition' : 'multipart/form-data'
        }
      })

改成

this._http.post('/api/Media/upload', formData)

【讨论】:

  • 相同,再次 401。无法联系到UpdatePicture()。而且,HttpContext 没有Current
【解决方案2】:

请删除以下行并重试:

'Content-Type': fileToUpload.type,

客户端:

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)
{


}

另一种方法是从 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)
    {
       ....
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    相关资源
    最近更新 更多