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?
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.
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)
}
}
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