Here is my task:
I need to upload immages to a server using Asp.Net web api.
I need to check file's extension before uploading it (I want to allow uploading only immages).
I need to get the file as a Stream or Base64String as I want to resize it before saving to server.
Here is what I've tried.
I am able to upload file to server, using MultipartFormDataStreamProvider, and after I've inhereted my CustomMultipartFormDataStreamProvider from that MultipartFormDataStreamProvider, I was able to check file-extension in the GetStream method like:
public override Stream GetStream(HttpContent parent, System.Net.Http.Headers.HttpContentHeaders headers)
{
if (!String.IsNullOrEmpty(headers.ContentDisposition.FileName))
{
var fileExtension = CommonUtils.GetFileExtension(headers.ContentDisposition.FileName);
if (_allowedExtensions != null && !_allowedExtensions.Contains(fileExtension.ToLower()))
{
return Stream.Null;
}
}
return base.GetStream(parent, headers);
}
But MultipartFormDataStreamProvider saves file to the specified folder and not returning a Stream, and if I want to resize it, I need to read it from the HDD, resize, save as new file and delete the old one.
The other variant is to use MultipartMemoryStreamProvider - here I can get a Stream:
var task = Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider())
.ContinueWith<HttpResponseMessage>((tsk) =>
{
MultipartMemoryStreamProvider provider = tsk.Result;
Stream stream = provider.Contents[0].ReadAsStreamAsync().Result;
String imageBase64 = Convert.ToBase64String(CommonUtils.StreamToByteArray(stream));
......
}
But with MultipartMemoryStreamProvider I don't know how to check file extension as I can't override method GetStream
Is there a way to both check file extension before uploading file and get a file as a Stream instead of saving it to the disc. Or the only way is to save->resize->save new->delete old?
I don't know how to check file extension as I can't override method GetStream
And why is that? Nothing stops you from overriding GetStream
For example:
public class ImageOnlyMultipartMemoryStreamProvider : MultipartMemoryStreamProvider
{
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
var fileExtension = CommonUtils.GetFileExtension(headers.ContentDisposition.FileName);
return _allowedExtensions == null || _allowedExtensions.Any(i => i.Equals(fileExtension , StringComparison.InvariantCultureIgnoreCase)) ? base.GetStream(parent, headers) : Stream.Null;
}
}
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