C # Two ways to implement web file uploads

Source: Internet
Author: User

1. C # Implementation of Web file upload

In web programming, we often need to upload some local files to the Web server, after uploading, users can easily browse these files through the browser, the application is very extensive.

So how do you use C # to implement file uploads? The following is a brief introduction.

First, in your Visual C # Web project, add an upload Web form, 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 it becomes a service-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 properties of <form> must be set to:

<form method=post enctype=multipart/form-data runat= "Server" >

Without this attribute, uploads cannot be implemented.

Then add a button to the Web Form class in this Web form, and double-click the button to include the following code:

//Upload a picture's program segment
DateTime now = DateTime.Now;
Take the current time to the object of the Datatime class now
String strbaselocation = "D:\web\FC\pic\";
This is the absolute directory of the server to which the file will be uploaded
if (PreviousFile1.PostedFile.ContentLength! = 0)//Determines whether the selected file length of the selection dialog is 0
{
     PreviousFile1.PostedFile.SaveAs (Strbaselocation+now. Dayofyear.tostring () +previousfile1.postedfile.contentlength.tostring () + ". jpg");
//Perform the upload and automatically name the file according to the date and file size, ensuring that no duplicates
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 is used in the author's development of a system that uses XML files to store news information, the next few lines of code is to write the upload file information into the XML file. If you want to upload other types of files, you only need to change the JPG to the appropriate type of suffix name, such as doc to upload Word files, the browser can directly browse the uploaded Word file.

"Precautions"

1. Upload files can not be unlimited;

2. Be aware of the security aspects of IIS coordination;

3. When installing the installation program with Visual Studio, please be aware of the absolute path problem where the installer is located;

4. Note the problem of duplicate file name after uploading.

2. C # Implementation of Web file upload

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 implement the corresponding function of the player's upload file function in the player's submission.
</summary>
public class FileUpload
{
public enum File//defines an array that a person uses to store information about the player's uploaded 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)//main function to implement the player file upload function
{
string[] arr = new STRING[5];
String FileName = Getuniquelystring (); Get 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<=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 file name that is not duplicated
{
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;
}
}
}

C # Two ways to implement web file uploads

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.