user2330270 user2330270 - 3 months ago 37
C# Question

Content-Disposition is always null in web api 2

I have a very simple form:

<form id="upload" enctype="multipart/form-data" action="~/Api/File/Post" method="post" >
<input type="file" name="files[0].media" />
<input type="submit" value="Submit" />
</form>


When debugging I get the file, but
fileData.Headers.ContentDisposition
is always null so I can not access the file name. I dont see any other property in the Request object to get the file name.

What confuses me the most is inspecting the request with chromes debugger shows the following details

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Content-Type:multipart/form-data; boundary=----WebKitFormBoundary3rLRRBQX6jj7MbWU
------WebKitFormBoundary3rLRRBQX6jj7MbWU
Content-Disposition: form-data; name="files[0].media"; filename="MyFileName.mp4"
Content-Type: video/mp4


------WebKitFormBoundary3rLRRBQX6jj7MbWU--


Any ideas? This looks like it is being sent correctly... (removed file name in example above)

Answer

Given the html form provided in your question you should be able to access the file data using the following code:

[HttpPost]
public async Task<IHttpActionResult> Post()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return this.StatusCode(HttpStatusCode.UnsupportedMediaType);
    }

    var filesProvider = await Request.Content.ReadAsMultipartAsync();
    var fileContents = filesProvider.Contents.FirstOrDefault();
    if (fileContents == null)
    {
        return this.BadRequest("Missing file");
    }

    var headers = fileContents.Headers;
    string filename = headers.ContentDisposition.FileName;
    Stream fileStream = await fileContents.ReadAsStreamAsync();

    ... do something with the file name and stream
}