简体   繁体   English

在Web API 2中Content-Disposition始终为null

[英]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. 调试时,我得到文件,但是fileData.Headers.ContentDisposition始终为null,因此无法访问文件名。 I dont see any other property in the Request object to get the file name. 我没有在Request对象中看到任何其他属性来获取文件名。

What confuses me the most is inspecting the request with chromes debugger shows the following details 最让我感到困惑的是使用chromes调试器检查请求显示了以下详细信息

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) 看起来好像发送正确了...(上面示例中的文件名已删除)

Given the html form provided in your question you should be able to access the file data using the following code: 给定问题中提供的html表单,您应该可以使用以下代码访问文件数据:

[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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM