Determine the file format and size before uploading the image to verify whether the file is an image

  • 2020-11-25 07:13:46
  • OfStack

In my recent work, I need to upload a picture. Since what I am uploading is a picture, I should verify the file 1 times before uploading to see if it is a picture file. Verify the format of the selected file before uploading. When uploading images, due to limited server resources, the maximum number of images is often stipulated, so the size of the image should be verified before uploading. So let's do 1 of these two tests today.

Verify the file type to see if the selected file is an image:
 
// File type:  
protected bool IsAllowableFileType(string FileName) 
{ 
// from web.config Read determines the file type limit  
string stringstrFileTypeLimit; 
stringstrFileTypeLimit = ConfigurationManager.AppSettings["PicTureTye"].ToString(); 
// Whether the current file extension is included in this string  
Response.Write(FileName + stringstrFileTypeLimit); 
if (stringstrFileTypeLimit.IndexOf(FileName.ToLower()) != -1) 
{ 
return true; 
} 
else 
{ 
return false; 
} 
} 

Verify the file size to see if the file has exceeded the maximum limit:
 
// The file size  
public bool IsAllowableFileSize(long FileContentLength) 
{ 
// from web.config Read limits for determining file sizes  
Int32 doubleiFileSizeLimit; 
doubleiFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]); 

// Determine if the file exceeds the limit  
if (doubleiFileSizeLimit > FileContentLength) 
{ 
return true; 
} 
else 
{ 
return false; 
} 
} 

Below is the configuration file setting, which specifies the extension and size of the uploaded file.
 
<appSettings> 
<add key="PicTureTye" value=".jpg|.gif|.png|.bmp|.jpeg|"/> 
<add key="FileSizeLimit" value="512000"/> 
</appSettings> 

The code is very simple, as long as you call these two methods before uploading, you can upload the file to perform 1 simple verification, not only for image uploading, but also for other files, as long as you need to modify 1 configuration file.

Related articles: