.net Web API – working with files

public async Task PostFormData()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}

string root = HttpContext.Current.Server.MapPath(“~/App_Data”);
var provider = new MultipartFormDataStreamProvider(root);
string serverFile = null;

try
{
await Request.Content.ReadAsMultipartAsync(provider);

foreach (MultipartFileData file in provider.FileData)
{

Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine(“Server file path: ” + file.LocalFileName);

// var stream = file.ReadAsStreamAsync();
using (StreamReader sr = new StreamReader(file.LocalFileName))
{
var line = await sr.ReadToEndAsync();
var res = line;
}
}

foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
var test = string.Format(“{0}: {1}”, key, val);
}
}

return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
finally
{
if(string.IsNullOrEmpty(serverFile))
File.Delete(serverFile);
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s