ASP. NET uploads image files
Last Update:2018-12-06
Source: Internet
Author: User
Using system;
Using system. IO; public partial class _ default: system. Web. UI. Page
{
Protected void btnupload_click (Object sender, eventargs E)
{
If (ispostback)
{
Boolean fileok = false; // defines the variable to determine whether the file is an image.
String Path = server. mappath ("~ /Uploadedimages/"); // specifies the file storage path if (fuupload. hasfile) // determines whether the control selects a file
{
String fileextension = path. getextension (fuupload. filename). tolower (); // use this method to get the extension of the uploaded file
String [] allowedextensions = {". GIF ",". PNG ",". JPEG ",". jpg "}; // defines the extended for (INT I = 0; I <allowedextensions. length; I ++)
{
If (fileextension = allowedextensions [I]) // If the uploaded file passes Detection
{
Fileok = true; // set this variable to true
}
}
} If (fileok) // determines whether the detection is successful
{
Try
{
If (! Directory. exists (PATH) // use the directory class method to determine whether the stored path directory exists
{
Directory. createdirectory (PATH); // create the directory if it does not exist
}
Fuupload. postedfile. saveas (path + fuupload. filename );
Label1.text = "File Uploaded! ";
}
Catch (exception ex)
{
Label1.text = "file cocould not be uploaded." + ex. message;
}
}
Else
{
Label1.text = "cannot accept files of this type .";
}
}
String strfilename = fuupload. filename;
}
}
Html_code: <% @ Page Language = "C #" autoeventwireup = "true" codefile = "default. aspx. cs" inherits = "_ default" %> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Asp: fileupload id = "fuupload" runat = "server" Height = "24px" style = "Z-index: 100;
Left: pixel PX; position: absolute; top: 84px "width =" 480px "/>
<Asp: Label id = "label1" runat = "server" style = "Z-index: 103; left: pixel; position: absolute;
Top: 52px "width =" 476px "> </ASP: Label>
<Asp: button id = "btnupload" runat = "server" Height = "24px" onclick = "btnupload_click"
Style = "Z-index: 102; left: pixel PX; position: absolute; top: 124px" text = "Upload" width = "84px"/>
</Div>
</Form>
</Body>
</Html>