// Determine whether the uploaded file is an image
Private static bool IsAllowedExtension (FileUpload upfile)
{
String strOldFilePath = "";
String strExtension = "";
String [] arrExtension = {". gif", ". jpg", ". bmp", ". png "};
If (upfile. PostedFile. FileName! = String. Empty)
{
StrOldFilePath = upfile. PostedFile. FileName; // obtain the complete path name of the file.
StrExtension = strOldFilePath. Substring (strOldFilePath. LastIndexOf ("."); // obtain the file extension, such as. jpg.
For (int I = 0; I <arrExtension. Length; I ++)
{
If (strExtension. Equals (arrExtension [I])
{
Return true;
}
}
}
Return false;
}
// Upload and rename the image
Protected void FileUpload_Button_Click (object sender, EventArgs e)
{
Try
{
If (FileUpload1.HasFile)
{
If (IsAllowedExtension (FileUpload1 ))
{
String filepath = FileUpload1.FileName;
// String filename = filepath. substring (filepath. lastIndexOf ('\') + 1, filepath. length-filepath. lastIndexOf ('\')-1); // (filepath. lastIndexOf ("\") + 1 );
// Rename the image in mm-mm
String filename = DateTime. now. toString ("yyyy-MM-dd-hh-mm-ss-fffffff") + filepath. substring (filepath. lastIndexOf ('. '), filepath. length-filepath. lastIndexOf ('. '));
// Set the upload path (absolute path)
String uppath = Server. MapPath ("~ /Photo/") + filename;
// Upload the image to the absolute path www.2cto.com
FileUpload1.PostedFile. SaveAs (uppath );
// Set the database storage path
String savepath = "~ \ Photo \ "+ filename;
HiddenField1.Value = savepath;
LblInfo. Text = "Upload successful! ";
}
}
Else
{
LblInfo. Text = "Select Upload File ";
}
}
Catch (Exception ex)
{
LblInfo. Text = "Upload error! The reason is: "+ ex. ToString ();
}
}
<BR>
<BR>
Three Controls on the foreground
Front-end code:
?
<Asp: fileUpload ID = "FileUpload1" runat = "server" Font-Size = "13px" BorderColor = "Gray" BorderStyle = "Solid" BorderWidth = "1px" Height = "25px" Width = "400px"/>
<Asp: Button ID = "FileUpload_Button" runat = "server" Text = "Upload image" Height = "25px"
CausesValidation = "False" onclick = "FileUpload_Button_Click"/>
<Asp: Label id = "lblInfo" runat = "server" ForeColor = "Red" Font-Size = "13px"> </asp: Label>
Note:
1. The FileUpload control cannot be placed in the UpdatePanel control. If it is placed in the UpdatePanel control, the value of FileUpload1.HasFile is always false.
2. When filling data in the insert statement, use cmd. parameters. the format of AddWithValue ("@ B", savepath); prevents '\' escaping in the string savepath. If string SQL = string is used. format ("insert into table1 (path) values ('{0}')", savepath); Format, the image path stored in the database will not have '\'.
3. If there is a verification control in the Image Upload page and you do not want to verify it when you click the image upload button, add the CausesValidation = "False" attribute.
From Miko2012