0

I'm trying to create a POST api controller for my .NET Core 3.1 web app so gamers can upload screenshots of their gaming experiences.

This is a little different scenario, because this API will be used by a Unity game that is compiled into WebGL.

So I am thinking I can't use [FromForm].

Anyway, I wrote this:

    [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();

    }

I am testing in postman.

I am sending it as

"Content-Type: application/octet-stream"

as my header and 'binary' as my body.

In Postman, when I select 'binary', it gives me an option to choose a file to use.

So I select a file to test and hit the Send button.

But I just get this back:

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

What could I be doing wrong?

Thanks!

SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185
  • 1
    Debug this action when you are sending data via postman and check if Request.Body contains your data. If it has then just remove parameter and parse it manually. – Krystian Sitek Jun 09 '20 at 19:08

2 Answers2

1

Try using [FromForm] not [FromBody]. It should work.

1

Usually, files can be submitted through the form, and receive the it in the form of [FromForm]IFormFile in the background. Since you need to use [FromBody], you can first encode the file into a base64 string, pass it to the background as json format, and then decode it and do the upload.

Encode:

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

Decode:

Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
mj1313
  • 7,930
  • 2
  • 12
  • 32