【问题标题】:NetCore API controller will not accept files uploaded using FromBodyNet Core API 控制器将不接受使用 FromBody 上传的文件
【发布时间】:2020-09-29 01:38:35
【问题描述】:

我正在尝试为我的 .NET Core 3.1 Web 应用程序创建一个 POST api 控制器,以便游戏玩家可以上传他们游戏体验的屏幕截图。

这是一个稍微不同的场景,因为这个 API 将被编译成 WebGL 的 Unity 游戏使用。

所以我想我不能使用 [FromForm]。

反正我是这样写的:

    [HttpPost]
    public async Task<IActionResult> SubmitScreens([FromBody] IFormFile file)
    {
        //C:\inetpub\wwwroot\gamerProfiles\screenGrabs\
        string contentRootPath = _hostingEnvironment.ContentRootPath;

        // get the folder path
        var uploads = Path.Combine(contentRootPath, "pic_upload_testing");

        // make the file path for the uploading
        var filePath = Path.Combine(uploads, file.FileName);

        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(fileStream);
        }
        return Ok();

    }

我正在邮递员中进行测试。

我将其发送为

"Content-Type: application/octet-stream"

作为我的标题和“二进制”作为我的正文。

在 Postman 中,当我选择“二进制”时,我可以选择要使用的文件。

所以我选择了一个文件进行测试并点击发送按钮。

但我只是得到了这个:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "traceId": "|dc4efc3f-45ae830112e6f778."
}

我做错了什么?

谢谢!

【问题讨论】:

  • 当您通过邮递员发送数据时调试此操作并检查 Request.Body 是否包含您的数据。如果它已经删除参数并手动解析它。

标签: asp.net-core postman asp.net-core-webapi asp.net-core-3.0


【解决方案1】:

尝试使用 [FromForm] 而不是 [FromBody]。它应该可以工作。

【讨论】:

  • 您好,谢谢,但是将使用此 API 的应用程序/游戏没有表单。
【解决方案2】:

通常可以通过表单提交文件,后台以[FromForm]IFormFile的形式接收。由于需要使用[FromBody],所以可以先将文件编码成base64字符串,以json格式传到后台,再解码上传。

编码:

Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);

解码:

Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);

【讨论】:

  • 谢谢!这会进入我的 using filestream 语句吗?
  • 另外,“将其传递到后台”是什么意思?谢谢
  • @SkyeBoniwell 你可以参考这个link,这里的背景就是你的api控制器。
猜你喜欢
  • 2020-05-10
  • 2021-01-10
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多