I just migrated an ASP.NET WebAPI to ASP.NET Core 2.1 (I also tried 2.2). It contains a file upload route which receives a multipart request a binary file, with a known key / name.
My issue is that request.Form.Files
collection is empty. The binary content is received as a normal form value (which only shows weird characters when parsed).
My understanding is that the clients' implementation is wrong. They are however mobile applications, so I have to stay backwards compatible. This is basically how the client is sending the file:
var client = new HttpClient();
var content = new MultipartFormDataContent();
content.Add(new ByteArrayContent(File.ReadAllBytes("someimage.jpg")), "file");
await client.PutAsync("https://myapi/api/document", content);
The old ASP.NET Implementation parsed it like this (some parts removed):
var provider = new MultipartMemoryStreamProvider();
await request.Content.ReadAsMultipartAsync(provider);
Stream file = null;
foreach (var contentPart in provider.Contents)
{
if (partName.Equals("file", StringComparison.OrdinalIgnoreCase))
{
file = await contentPart.ReadAsStreamAsync();
}
}
In ASP.NET Core, file/form parsing is built in and MultipartMemoryStreamProvider no longer exists, so this is what I implemented:
public async Task<IActionResult> Put(IFormFileCollection files) // files is empty list
public async Task<IActionResult> Put(IFormFile file) // file is null
// ...
var formFile = request.Form.Files.GetFile("file");
// formFile is null
// requests.Form.Files is empty
Stream file = formFile.OpenReadStream();
The file can be retrieved via request.Form["file"]
, but its content is displayed as {����
. No idea if I can get that back to my binary content.
I tried this code, but the file cannot be opened afterwards.
var fff = request.Form["file"];
using (var stream = System.IO.File.OpenWrite("out.jpg"))
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(fff);
}