C # Implementation of Web file upload two methods of instance code

Source: Internet
Author: User
Tags datetime file size file system file upload
In web programming, we often need to upload some local files on the Web server, after uploading, users can easily browse these files through the browser, the application is very extensive.

1. C # Implementation of Web file upload
How do I use C # to implement file upload? The following is a brief introduction.
First, add an uploaded Web form to your Visual C # Web project, and in order to upload the file, you need to select the HTML class's File field control in Toolbox to add the control to the Web form. At this point, however, the control is not a server-side control, and we need to add the following code to it: <input id=previousfile1 type=file size=49 runat= "Server" so that it becomes a server-side control, If you need to upload several files at the same time, we can add this control accordingly.
It is important to note that the code must set the properties of <form> to be:

Copy Code code as follows:


&lt;form method=post enctype=multipart/form-data runat= "Server" &gt;


Without this attribute, uploads cannot be implemented.
Then add a button for the Web Form class in this Web Form and double click the button for the following code:

Copy Code code as follows:


//Upload picture of the program section


DateTime now = DateTime.Now;


//Time to datatime objects now


string strbaselocation = "D:webfcpic";


//This is the absolute directory where the files will be uploaded to the server


if (PreviousFile1.PostedFile.ContentLength!= 0)//Determine if the selection dialog box chooses a file length of 0


{


PreviousFile1.PostedFile.SaveAs (Strbaselocation+now. Dayofyear.tostring () +previousfile1.postedfile.contentlength.tostring () + ". jpg");


//execute uploads and automatically name files based on date and file size to ensure that they are not duplicated


label1.text= "Picture 1 has been uploaded, the file name is:" +now. Dayofyear.tostring () +previousfile1.postedfile.contentlength.tostring () + ". jpg";


Navigator. Insert (System.Xml.TreePosition.After, XmlNodeType.Element, "Pic1", "", "");


Navigator. Insert (System.Xml.TreePosition.FirstChild, XmlNodeType.Text, "Pic1", "", "");


Navigator. Value= now. Dayofyear.tostring () +previousfile1.postedfile.contentlength.tostring () + ". jpg";


Navigator. Movetoparent ();


}


The above code for the author developed a use of XML files to store news information System, the next few lines of code to write upload file information to the XML file. If you want to upload other types of files, just need to change JPG to the appropriate type of suffix name, such as doc can upload Word file, browser can directly browse the uploaded Word file.
"Precautions"
1. Upload file can not be unlimited;
2. Be aware of the security aspects of IIS coordination;
3. When installing programs with visual Studio installations, be aware of the absolute path problem of the installer;
4. Note the name of the file upload after the problem.

2. C # Implementation of Web file upload

Copy Code code as follows:




using System;


using System.Data;


using System.Data.SqlClient;


using System.Web.UI.HtmlControls;


using System.Drawing.Imaging;


using System.Configuration;


using System.Drawing;


namespace Zhuanti


{


///&lt;summary&gt;


///This is a functional module for player contributors to implement the corresponding functions used in the Upload file function


///&lt;/summary&gt;


public class FileUpload


{


public enum File//defines an array that a person uses to store information about a player uploading files


{


file_size,//Size


file_postname,//type (file suffix name)


File_sysname,//system name


File_orginname,//original name


file_path//file path


}


private static Random rnd = new Random (); Get a random number


public static string[] UploadFile (htmlinputfile file,string Upload_dir)//implementation of the player file upload function of the main function


{


string[] arr = new STRING[5];


string FileName = Getuniquelystring (); Gets a file name that is not duplicated


string fileorginname = file. PostedFile.FileName.Substring


(file. PostedFile.FileName.LastIndexOf ("") +1);//Get the original name of the file


if (file. postedfile.contentlength&lt;=0)


{return null;}


string Postfilename;


string FilePath = Upload_dir.tostring ();


string path = FilePath + "";


Try


{


int pos = file. PostedFile.FileName.LastIndexOf (".") +1;


Postfilename = file. PostedFile.FileName.Substring (Pos,file. Postedfile.filename.length-pos);


file. Postedfile.saveas (path+filename+ ".") +postfilename); Stores the specified file to the specified directory


}


catch (Exception exec)


{


throw (exec);


}


double unit = 1024;


Double size = math.round (file. postedfile.contentlength/unit,2);


arr[(int) file.file_size] = SIZE. ToString (); File Size


arr[(int) file.file_postname] = Postfilename; File type (file suffix name)


arr[(int) file.file_sysname] = FileName; File System name


arr[(int) file.file_orginname] = Fileorginname; The original name of the file


arr[(int) file.file_path]=path+filename+ "." +postfilename; File path


return arr;


}


public static bool Operatedb (string sqlstr)//Establish an association with the database


{


if (sqlstr==string.empty)


return false;


SqlConnection myconnection = new SqlConnection (configurationsettings.appsettings["connstring"]);


SqlCommand mycommand = new SqlCommand (sqlstr, MyConnection);


Myconnection.open ();


Mycommand.executenonquery ();


Myconnection.close ();


return true;


}


public static string getuniquelystring ()//Get a duplicate filename


{


const int random_max_value = 1000;


string Strtemp,stryear,strmonth,strday,strhour,strminute,strsecond,strmillisecond;


DateTime DT =datetime.now;


int rndnumber = rnd. Next (Random_max_value);


stryear = dt. Year.tostring ();


strmonth = (dt. Month &gt; 9)? Dt. Month.tostring (): "0" + dt. Month.tostring ();


strday = (dt. Day &gt; 9)? Dt. Day.tostring (): "0" + dt. Day.tostring ();


Strhour = (dt. Hour &gt; 9)? Dt. Hour.tostring (): "0" + dt. Hour.tostring ();


Strminute = (dt. Minute &gt; 9)? Dt. Minute.tostring (): "0" + dt. Minute.tostring ();


Strsecond = (dt. Second &gt; 9)? Dt. Second.tostring (): "0" + dt. Second.tostring ();


Strmillisecond = dt.Millisecond.ToString ();


strtemp = stryear + strmonth + strday + "_" + Strhour + strminute + Strsecond + "_" + Strmillisecond + "_" + Rndnumber.tos Tring ();


return strtemp;


}


}


}

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.