Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate file uploads in ASP.NET Web API

I want to validate the file extension of file uploads in ASP.NET Web API (note: I realize that this is not a full-proof method of validation).

I'm using the MultipartFormDataStreamProvider to process the POSTed file. Since Request.Content.Headers.ContentDisposition is null before the provider processes the file (via ReadAsMultipartAsync), where is the best place to validate the file name of the request?

like image 783
Ben Foster Avatar asked Sep 04 '12 08:09

Ben Foster


People also ask

How do you validate upload files?

Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code.


1 Answers

You can inherit from MultipartFormDataStreamProvider and override either GetLocalFileName (runs after reading content into stream) or GetStream (runs prior to reading content into the stream). In both cases you have access to headers.ContentDisposition.FileName

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path)
        : base(path)
    {
    }

    public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
    {
        //validate headers.ContentDisposition.FileName as it will have the name+extension
        //then do something (throw error, continue with base or implement own logic)
    }

    public override Stream GetStream(HttpContent parent, System.Net.Http.Headers.HttpContentHeaders headers)
    {
        //validate headers.ContentDisposition.FileName as it will have the name+extension

        //then do something (throw error, continue with base or implement own logic)
    }
}
like image 55
Filip W Avatar answered Sep 28 '22 11:09

Filip W