In Asp.net 2.0, when uploading images, it is often necessary to determine whether the image uploaded by the user meets the specified specifications,
You can use the following
Code Fragment.
First, set the size limit for image uploading in the web. config file, such
<Deleetask>
<Add key = "requiredheight" value = "184"/>
<Add key = "requiredwidth" value = "370"/>
</Appsettings>
Then, obtain the pre-set size in the web. config file on the page.
If (page. ispostback) {Height = convert. toint32 (configurationmanager. appsettings. get ("requiredheight"); width = convert. toint32 (configurationmanager. appsettings. get ("requiredwidth "));}
Then write the following code in the Event code of the "Upload" button:
If (page. isvalid)
{
If (fileupload1.hasfile)
{
String extension = path. getextension (fileupload1.postedfile. filename );
Switch (extension. tolower ())
{
Case ". GIF ":
Case "jpg ":
Try
{
// If the dimension is correct
If (validatefiledimensions ())
{
String filename = path. getfilename (fileupload1.postedfile. filename );
String saveasname = path. Combine (server. mappath ("~ /Uploads/"), filename );
Fileupload1.postedfile. saveas (saveasname );
Lblsucces. Visible = true;
}
Else
{
Valinvaliddimensions. isvalid = false;
Valinvaliddimensions. errormessage = string. Format (valinvaliddimensions. errormessage, height, width );
}
}
Catch
{
// Unable to read the file dimensions. the uploaded file is probably not an image.
Valinvalidfile. isvalid = false;
}
Break;
Default: // the uploaded file has an incorrect Extension
Valinvalidfile. isvalid = false;
Break;
}
}
}
Public bool validatefiledimensions ()
{
Using (system. Drawing. Image myimage = system. Drawing. image. fromstream (fileupload1.postedfile. inputstream ))
{
Return (myimage. Height = height & myimage. width = width );
}
}
Check that the dimension determination process is completed in validatefiledimensions ().
Finally, some verification controls are displayed on the page.
<Form ID = "form1" runat = "server">
<Div>
<Asp: fileupload id = "fileupload1" runat = "server"/>
<Asp: button id = "btnupload" runat = "server" onclick = "btnupload_click" text = "Upload File"/>
<Br/>
<Asp: requiredfieldvalidator id = "valfileupload1" controltovalidate = "fileupload1" errormessage = "You must select a file first." runat = "server" display = "dynamic"/>
<Asp: customvalidator id = "valinvalidfile" runat = "server" errormessage = "the file you uploaded doesn't appear to be a valid image. "display =" dynamic "> </ASP: customvalidator>
<Asp: customvalidator id = "valinvaliddimensions" runat = "server" errormessage = "the image you uploaded has incorrect dimensions. please select a file with a height of {0} PX and a width of {1} PX. "display =" dynamic "enableviewstate =" false "> </ASP: customvalidator>
<Asp: Label id = "lblsucces" runat = "server" text = "the file you uploaded has been saved to disk successfully. "visible =" false "enableviewstate =" false "> </ASP: Label>
</Div>
</Form>