C # example code of Two Methods for uploading Web files

Source: Internet
Author: User

1. C # upload Web files
Using C # How to Implement the file upload function? The following is a brief introduction.
First, add a web Form for uploading in your Visual C # Web project. to upload files, select the File Field control of the HTML class in ToolBox, add this control to Web Form. However, this control is not a server control yet. We need to add the following code to it: <input id = previusfile1 type = file size = 49 runat = "server"> in this way, it becomes a server control. If you need to upload multiple files at the same time, we can add this control accordingly.
Note that the <form> attribute must be set:
Copy codeThe Code is as follows:
<Form method = post encType = multipart/form-data runat = "server">

If you do not have this attribute, you cannot upload it.
Then add a Button of the Web Form class to the Web Form, and double-click the Button to add the following code:
Copy codeThe Code is as follows:
// Program segment for uploading images
DateTime now = DateTime. Now;
// Get the current time to the object now of the DataTime class
String strBaseLocation = "D: \ web \ FC \ pic \";
// This is the absolute directory of the server to which the file will be uploaded
If (previusfile1.postedfile. ContentLength! = 0) // determine whether the selected file length is 0
{
Previusfile1.postedfile. SaveAs (strBaseLocation + now. DayOfYear. ToString () + previusfile1.postedfile. ContentLength. ToString () + ". jpg ");
// Execute the upload and automatically name the File Based on the date and file size to ensure that the file is not repeated.
Label1.Text = "Image 1 has been uploaded. The file name is:" + now. DayOfYear. ToString () + previusfile1.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 () + previusfile1.postedfile. ContentLength. ToString () + ". jpg ";
Navigator. MoveToParent ();
}

The above code is used in a system developed by the author to store news information using an XML file. The following code is used to write and upload file information to an XML file. If you want to upload other types of files, you only need to change the jpg file to the corresponding type of suffix name. For example, you can change it to doc to upload the Word file, and the browser can directly browse the uploaded Word file.
[Note]
1. the file to be uploaded cannot be infinitely large;
2. Pay attention to the security of IIS;
3. When using the Visual Studio installation project for installation, pay attention to the absolute path of the installation program;
4. Pay attention to the file name duplication problem after upload.

2. C # upload Web files
Copy codeThe Code is 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
{
/// <Summary>
/// This is a function module used to enable the player's file upload function in the player's contribution.
/// </Summary>
Public class FileUpload
{
Public enum File // defines an array used by a person to store the information of files uploaded by players.
{
FILE_SIZE, // size
FILE_POSTNAME, // type (File suffix)
FILE_SYSNAME, // system name
FILE_ORGINNAME, // Original Name
FILE_PATH // file path
}
Private static Random rnd = new Random (); // obtain a Random number
Public static string [] UploadFile (HtmlInputFile file, string Upload_Dir) // main function that implements the Player file upload function
{
String [] arr = new String [5];
String FileName = GetUniquelyString (); // get a non-repeated file name
String FileOrginName = file. PostedFile. FileName. Substring
(File. PostedFile. FileName. LastIndexOf ("\") + 1); // get the original name of the file
If (file. PostedFile. ContentLength <= 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); // store 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)
Arr [(int) File. FILE_SYSNAME] = FileName; // File system name
Arr [(int) File. FILE_ORGINNAME] = FileOrginName; // original File name
Arr [(int) File. FILE_PATH] = path + FileName + "." + postFileName; // File path
Return arr;
}
Public static bool OperateDB (string sqlstr) // create an association with the database
{
If (sqlstr = String. Empty)
Return false;
SqlConnection myConnection = new SqlConnection (ConfigurationSettings. etettings ["connstring"]);
SqlCommand myCommand = new SqlCommand (sqlstr, myConnection );
MyConnection. Open ();
MyCommand. ExecuteNonQuery ();
MyConnection. Close ();
Return true;
}
Public static string GetUniquelyString () // get a non-repeated file name
{
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> 9 )? Dt. Month. ToString (): "0" + dt. Month. ToString ();
StrDay = (dt. Day> 9 )? Dt. Day. ToString (): "0" + dt. Day. ToString ();
StrHour = (dt. Hour> 9 )? Dt. Hour. ToString (): "0" + dt. Hour. ToString ();
StrMinute = (dt. Minute> 9 )? Dt. Minute. ToString (): "0" + dt. Minute. ToString ();
StrSecond = (dt. Second> 9 )? Dt. Second. ToString (): "0" + dt. Second. ToString ();
StrMillisecond = dt. Millisecond. ToString ();
StrTemp = strYear + strMonth + strDay + "_" + strHour + strMinute + strSecond + "_" + strMillisecond + "_" + rndNumber. ToString ();
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.