Skip to content

Instantly share code, notes, and snippets.

@ajtowf
Created April 30, 2013 15:48
Show Gist options
  • Save ajtowf/5489597 to your computer and use it in GitHub Desktop.
Save ajtowf/5489597 to your computer and use it in GitHub Desktop.
WebApi PostingFiles
[ActionName("Index"), HttpPost]
public async Task<HttpResponseMessage> CreateAttachment(...)
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string attachmentsDirectoryPath = HttpContext.Current.Server.MapPath("~/SomeDir/");
if (!Directory.Exists(attachmentsDirectoryPath))
{
Directory.CreateDirectory(attachmentsDirectoryPath);
}
var provider = new MultipartFormDataStreamProvider(attachmentsDirectoryPath);
var result = await Request.Content.ReadAsMultipartAsync(provider);
if (result.FileData.Count < 1)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
var fileData = result.FileData.First();
string filename = fileData.Headers.ContentDisposition.FileName;
Do stuff ...
File.Delete(fileData.LocalFileName);
return Request.CreateResponse(HttpStatusCode.Created, ...);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment