Tuesday, 11 March 2008

Validating Images before Upload by Checking the File Stream

Rather than just checking for valid file extensions, there are more advanced ways of checking that your users are not uploading rubbish to your image file store (we currently use MOSS for storage at my current client "LL").

Thanks to http://forums.asp.net/p/1051895/2171502.aspx#2171502 for the image validation part of this code.



/// <summary>
/// Added to validate that an image is being uploaded - not just any document
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private bool IsImage(byte[] data)
{
//read 64 bytes of the stream only to determine the type
string myStr = System.Text.Encoding.ASCII.GetString(data).Substring(0, 16);
//check if its definately an image.
if (myStr.Substring(8, 2).ToString().ToLower() != "if")
{
//its not a jpeg
if (myStr.Substring(0, 3).ToString().ToLower() != "gif")
{
//its not a gif
if (myStr.Substring(0, 2).ToString().ToLower() != "bm")
{
//its not a .bmp
if (myStr.Substring(0, 2).ToString().ToLower() != "ii")
{
//its not a tiff
//ProcessErrors("notImage");
myStr = null;
return false;
}
}
}
}
myStr = null;
return true;
}





public Response<List<SharepointDocumentDto>> AddAssetImageToSession(
string fileName, Stream contentStream, IWebPageView currentView, string parentWindow)
{
Response<List<SharepointDocumentDto>> response = GetAssetImageSingle();

if (string.IsNullOrEmpty(fileName))
{
response.Errors.Add(new Error(ErrorName.FileError, Errors.MissingFileName));
response.IsSuccessful = false;
}


else
{
SharepointDocumentDto item = new SharepointDocumentDto();
item.Name = fileName; //Set FileName
item.IsNewItem = true; //Flag as true so we know to save it when the asset is saved
item.GeneratedListItemId = Guid.NewGuid().ToString();
MemoryStream ms = new MemoryStream();
byte[] data = new byte[256];
int c = contentStream.Read(data, 0, data.Length);

//Check if it is a valid image
if (!IsImage(data))
{
response.Errors.Add(new Error(ErrorName.FileError, Errors.InvalidImageUploaded));
response.IsSuccessful = false;
return response; //invalid
}

//Read into buffer until end of file
while (c > 0)


No comments: