2009-02-15 11:52:54| Category: Default Categories | Tags: | Report | Font size Big medium small subscription
ASP. NET (C #) FileUpload implements uploading files of limited type and size to server 2009-01-07 23:29
The upload file has two main destinations, one is the server, the other is the database, ASP. NET built-in FileUpload this upload control, the text box displays the full name of the file selected by the user.
Its properties mainly include:
Contenlength: Upload file size in bytes
FileName: File name
HasFile: Whether the file is selected
Example:
Test environment. NET 2.0 (with detailed instructions in)
Default.aspx
<%@ 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 ">
<title> Untitled Page </title>
<body>
<form runat= "Server" >
<div>
<asp:fileupload runat= "Server"/><br/>
<br/>
<asp:button runat= "Server" text= "upload"/> </div>
</form>
</body>
Default.aspx.cs
Copy Code
Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{
}
protected void Btnupload_click (object sender, EventArgs e)
{
Boolean fileOk = false;
String path = Server.MapPath ("~/upload/");
Determine if a file has been selected
if (fileupload1.hasfile)
{
Get the file extension and convert to lowercase
String fileextension = System.IO.Path.GetExtension (fileupload1.filename). ToLower ();
Limit upload of JPG and GIF images only
String[] allowextension = {". jpg", ". gif"};
Pair the types of uploaded files
for (int i = 0; i < allowextension.length; i++)
{
if (fileextension = = Allowextension[i])
{
FileOk = true;
Break
}
}
The size of the uploaded file to detect, limit the file maximum not more than 1M
if (FileUpload1.PostedFile.ContentLength > 1024000)
{
FileOk = false;
}
The final result
if (fileOk)
{
Try
{
FileUpload1.PostedFile.SaveAs (path + fileupload1.filename);
Response.Write ("<script type= ' text/javascript ' >window.alert (' upload success ') </script>");
}
Catch
{
Response.Write ("<script type= ' text/javascript ' >window.alert (' upload failed ') </script>");
}
}
Else
{
Response.Write ("<script type= ' text/javascript ' >window.alert (' file type or file size exceeds 1M ') </script>");
}