Phil Phil - 1 year ago 117
reST (reStructuredText) Question

How To Accept a File POST - ASP.Net MVC 4 WebAPI

I'm using mvc 4 webapi beta to build a rest service. I need to be able to accept POSTed images/files from client applications. Is this possible using the webapi? Below is how action I am currently using. Does anyone know of an example how this should work?

public string ProfileImagePost(HttpPostedFile profileImage)
string[] extensions = { ".jpg", ".jpeg", ".gif", ".bmp", ".png" };
if (!extensions.Any(x => x.Equals(Path.GetExtension(profileImage.FileName.ToLower()), StringComparison.OrdinalIgnoreCase)))
throw new HttpResponseException("Invalid file type.", HttpStatusCode.BadRequest);

// Other code goes here

return "/path/to/image.png";

Answer Source

see,-part-2, although I think the article makes it seem a bit more complicated than it really is.


public Task<HttpResponseMessage> PostFile() 
    HttpRequestMessage request = this.Request; 
    if (!request.Content.IsMimeMultipartContent()) 
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 

    string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads"); 
    var provider = new MultipartFormDataStreamProvider(root); 

    var task = request.Content.ReadAsMultipartAsync(provider). 
        ContinueWith<HttpResponseMessage>(o => 

        string file1 = provider.BodyPartFileNames.First().Value;
        // this is the file name on the server where the file was saved 

        return new HttpResponseMessage() 
            Content = new StringContent("File uploaded.") 
    return task; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download