Validating Images before Upload by Checking the File Stream
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 Lend Lease).
///summary
/// summary
{
//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
{
Response 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)
Reference:http://ddkonline.blogspot.com/2008/03/checking-for-valid-images-by-checking.html
Happy Programming
0 Comments:
Post a Comment
<< Home