FileUpload implementation File Upload example in asp.net

Source: Internet
Author: User
Tags file upload
Property:
FileName: Get the file name of the upload

HasFile: Whether to select (exist) uploaded files

contentlength: Gets the size of the file on the channeling, in bytes (byte)
Method:
Server.MapPath (): getting the physical path on the server

SaveAs (): Save the file to the specified folder
Note: By default, the upload file size is limited to 4MB, and the default settings can be modified by web.config.comments (this is a global configuration)
or change the application upload limit by modifying the web.config file.
Such as:
1
< httpRuntime maxRequestLength = "10240" executionTimeout = "150" enable = "true" />
Element Explanation:
maxRequestLength: Set the upload file size in KB.
executiontimeout: maximum number of seconds allowed to execute the request, this feature must not take effect until the Debug property in the compilation element is false.
Enable: Specifies whether the application domain (AppDomain) is enabled at the current node and child node level to accept incoming requests. If False, the application is actually closed. The default value is True.
The popular saying is: Whether to allow users to access the Web site (whether to allow HTTP requests)
Note: If the upload file exceeds the maxRequestLength size, there will be situations where the page cannot be displayed.
Such as:
Check File Upload type:
1). Client check (JavaScript implementation)

2). server-side Check
Example:
Interface Reference:

The code is as follows Copy Code

function Checktype () {





Get the value of the uploaded file


var Filename=document.getelementbyid ("FileUpLoad1"). Value;





Returns the last occurrence of the substring of a string object.


var seat=filename.lastindexof (".");





Returns a substring at the specified position in a string object and converts to lowercase.


var extension=filename.substring (seat). toLowerCase ();





To determine which file format is allowed to upload


if (extension!= ". jpg" &amp;&amp;extension!= ". jpeg" &amp;&amp;extension!= ". gif" &amp;&amp;extension!= ". png" &amp; &amp;extension!= ". bmp") {


Alert ("does not support uploading of" +extension+ "Files!");


return false;


}else{


return true;


//}





var allowed=[". jpg", ". gif", ". png", ". bmp", ". jpeg"];


for (Var i=0;i&lt;allowed.length;i++) {


if (!) ( Allowed[i]!=extension)) {


return true;


}


}


Alert ("Does not support" +extension+ "format");


return false;


}

. Aspx.cs:

The code is as follows Copy Code

File Upload button click event


protected void Btnfileupload_click (object sender, EventArgs e)


{





if (fileupload1.hasfile)


{


Determine if the file is less than 10Mb


if (FileUpLoad1.PostedFile.ContentLength &lt; 10485760)


{


Try


{


Upload file and specify path to upload directory


FileUpLoad1.PostedFile.SaveAs (Server.MapPath ("~/files/")


+ Fileupload1.filename);


* Note-&gt; Why not here: FileUpLoad1.PostedFile.FileName


* But: Fileupload1.filename?


* The former is to obtain the client full qualification (client full path) name


* The latter fileupload1.filename only get filename.


*/





Of course, upload statements can also be written like this (seemingly nonsense):


Fileupload1.saveas (@ "D:" +fileupload1.filename);





Lblmessage.text = "Upload success!";


}


catch (Exception ex)


{


Lblmessage.text = "abnormal, unable to upload!";


Lblmessage.text = ex. message;


}





}


Else


{


Lblmessage.text = "Upload file cannot be greater than 10mb!";


}


}


Else


{


Lblmessage.text = "File not selected!";


}


}

Server-side Check two ways:
1. Check the file name extension.


2. Read the binary of the file.

To check the file extension:

The code is as follows Copy Code
Determine if there are any uploaded files


if (fileupload1.hasfile)


{


Intercepts the extensions to upload files


string extension = Fileupload1.filename


. Substring (FileUpload1.FileName.LastIndexOf (".")). ToLower ();


string extension = System.IO.Path


. GetExtension (Fileupload1.filename). ToLower ();





Upload file is greater than 10MB


if (FileUpload1.PostedFile.ContentLength &lt; 10485760)


{


Set up file formats to support uploading


string[] Allowedextension =


{". jpg", ". gif", ". jpeg", ". bmp", ". png"};





for (int i = 0; i &lt; allowedextension. Length; i++)


{


Determine if the uploaded file extension is correct


if (!) ( Extension!= Allowedextension[i])


{


Try


{


Uploading files


FileUpload1.PostedFile.SaveAs (Server.MapPath ("~/files/") + Fileupload1.filename);


Lblmessage.text = "File upload success!";


Break


}


catch (Exception ex)


{


Lblmessage.text = "Error occurred, unable to upload!";


}


}


Else


{


Lblmessage.text = "does not support" + extension + "format file!";


}


}


}


Else


{


Lblmessage.text = "Upload file size can not exceed 10mb!";


}


}


Else


{


Lblmessage.text = "There is no upload file!";


}


The disadvantages of the above example approach, assuming that the upload file is a. wma file, the extension to the. jpg file will not be recognized and can still be uploaded.
Workaround: By reading the binary of the file, the first two bytes of each file are not the same, and the different file name extensions its
Binary front two bytes are different. We can detect file extensions in this way. The first two bytes of the. jpg file are: 255216
The first two bytes of the. gif file are: 7173,6677 is bmp,13780 is png;7790 is exe,8297 is rar.

Upload the same file name, file will be overwritten, we want to deal with the uniqueness of the file name how to do?

To upload file name uniqueness Processing:
1. Use time stamps
2. Using GUIDs (globally uniform identifiers)

Reads the binary of the file and handles the uniqueness of the file name:

The code is as follows Copy Code

protected void Btnupload_click (object sender, EventArgs e)


{


if (fileupload1.hasfile)


{


Determine if the file size is greater than 10MB


if (FileUpload1.PostedFile.ContentLength &lt; 10485760)


{


if (Checkfiletype ())


{


Try


{


/* Use timestamp to be accurate to milliseconds, SessionID, upload file size,


5-bit random number, to do upload file name uniqueness of processing * *


/* Random rd = new Random ();


String fileName = DateTime.Now.ToString ("yyyymmddhhmmssfff") +


Rd. Next (10000,99999) +


Session.SessionID +


FileUpload1.PostedFile.ContentLength +


System.IO.Path.GetExtension (Fileupload1.filename);





* * If the use of timestamp is still not enough insurance, you need absolutely unique


* Then you can use the GUID (the global unique identifier):*/


String fileName = Guid.NewGuid (). ToString () + System.IO.Path.GetExtension (fileupload1.filename);





FileUpload1.PostedFile.SaveAs (Server.MapPath ("~/files/") + FileName);





Lblmessage.text = "Upload file success!";


}


catch (Exception)


{


Lblmessage.text = "Unexpected exception cannot be uploaded!";


}


}


Else


{


Lblmessage.text = "This file format is not supported!";


}


}


Else


{


Lblmessage.text = "File size cannot exceed 10MB";


}


}


Else


{


Lblmessage.text = "File does not exist, please select File!";


}


}





Determine the type of file by reading the first two bytes of the file binary


private bool Checkfiletype ()


{


Get the absolute path to the client file


String File=fileupload1.postedfile.filename;





Create a file stream.


System.IO.FileStream fs = new System.IO.FileStream (file,system.io.filemode.open,system.io.fileaccess.read);





To create an object that reads the binary of a file


System.IO.BinaryReader br=new System.IO.BinaryReader (FS);





String Filetype=string.empty;





Reads the first byte of the file and increases the read position by one byte.


FileType = Br. ReadByte (). ToString ();





Reads the second byte and increases the read position by one byte.


FileType = Br. ReadByte (). ToString ();





/* If you do not know the first two bytes of the file binary, you can print it out:


* Response.Write (Filebinary);


*/





Allow extensions for uploaded files


String[] allowtedextension = {"255216", "7173", "6677"};





Determine whether to allow file types to be uploaded


foreach (String Allowex in Allowtedextension)


{


if (!) ( Allowex!= FileType))


{


return true;


}


}


return false;


}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.