I'm trying to get files uploaded with ASP.NET WebApi2. I'm trying out two options: the first is to have the file in memory. For that I use a piece of code that is an extension on the HttpContent class:
public static async Task<HttpPostedData> ParseMultipartAsync(this HttpContent postedContent)
{
var provider = await postedContent.ReadAsMultipartAsync();
var files = new Dictionary<string, HttpPostedFile>(StringComparer.InvariantCultureIgnoreCase);
var fields = new Dictionary<string, HttpPostedField>(StringComparer.InvariantCultureIgnoreCase);
string[] toegestaneExtensies = { ".jpg", ".jpeg", ".gif", ".png", ".pdf", ".txt", ".xlsx" };
foreach (var content in provider.Contents)
{
var fieldName = content.Headers.ContentDisposition.Name.Trim('"');
if (!string.IsNullOrEmpty(content.Headers.ContentDisposition.FileName))
{
bool geuploadBestandHeeftToegestaneExtensie = (toegestaneExtensies.Contains(Path.GetExtension(content.Headers.ContentDisposition.FileName)));
if ((content.Headers.ContentLength > 0) && geuploadBestandHeeftToegestaneExtensie)
{
var file = await content.ReadAsByteArrayAsync();
var fileName = content.Headers.ContentDisposition.FileName.Trim('"');
files.Add(fieldName, new HttpPostedFile(fieldName, fileName, file));
}
}
else
{
if (fieldName != "submit")
{
var data = await content.ReadAsStringAsync();
fields.Add(fieldName, new HttpPostedField(fieldName, data));
}
}
}
return new HttpPostedData(fields, files);
}
}
This throws an exception though, because FileName is not in the right format. I can see the filename being "normal" in the picture, but looking into ContentDisposition, FileName is suddenly "\"banana.jpg\"". Why is this?
The second thing I'm trying is to do is to save to disk. This seems to work, I can write the file to disk, but get the following error message:
"error writing MIME multipart body part to output stream" - "Access denied".
It is simply the following code:
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path)
{
}
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}
var streamProvider = new MultipartFormDataStreamProvider("d:/");
var t = await Request.Content.ReadAsMultipartAsync(streamProvider);
But no access is denied, the file is written, it wasn't there before, the file has a normal filename. What could be going on?
Even cleaner than nathfy's solution :
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With