简体   繁体   中英

Get original filename from MultipartFileData in c#

I have a POST request for file upload with a body similar to this one:

-----------------------------88481896131794
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain

Content
-----------------------------88481896131794
Content-Disposition: form-data; name="text"

asdf
-----------------------------88481896131794
Content-Disposition: form-data; name="email"

asdf@gmail.com

On Visual Studio 2015, I handle the request like this:

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);

And I get the file name using this code:

foreach (MultipartFileData file in provider.FileData)
{
   fi.name = Path.GetFileName(file.LocalFileName);
}

With this method I get a totally different name BodyPart_408513e3-60d8-42f5-bdf3-8df9742f833f and the name I need is the original one test.txt

Any idea on how can I get it? Thanks.

the file.LocalFileName takes the local file that was generated when saving the data from the POST request. To pull the actual filename of the file sent via the POST you have to use: file.Headers.ContentDisposition.FileName

foreach (MultipartFileData file in provider.FileData)
{
   fi.name = Path.GetFileName(file.Headers.ContentDisposition.FileName);
}

你可以试试下面的而不是file.LocalFileName

file.Headers.ContentDisposition.FileName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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