C # File Upload class

Source: Internet
Author: User
Upload

Using System;

namespace Upfile {///
Summary description of the upfile.
///
public class Upfile
{
private string path = null;
private string fileType = null;
private int sizes = 0;
///
Initializing variables
///
Public Upfile ()
{
Path = @ "\uploadimages\"; Upload path
FileType = "Jpg|gif|bmp";
sizes = 200; Size of file, default 200KB
}

///
Set up the upload path, such as: uploadimages\
///
public string Path
{
Set
{
Path = @ "\" + value + @ "\";
}
}

///
Set the upload file size in KB
///
public int Sizes
{
Set
{
Sizes = value * 1024;
}
}

///
Set the type of upload file, such as: Jpg|gif|bmp///
public string FileType
{
Set
{
FileType = value;
}
}

///
Upload pictures
///
Upload Control Name
True to create the folder at the current time, false to the Set folder
Returns the relative path of the uploaded picture
public string FileSaveAs (System.Web.UI.HtmlControls.HtmlInputFile name,bool creatdirectory)
{
Try
{
String Filepath=null;
Change the name of the picture or the name of the folder at the current time
String modifyfilename = DateTime.Now.Year.ToString () + DateTime.Now.Month.ToString () + DateTime.Now.Day.ToString () + DateTime.Now.Hour.ToString () + DateTime.Now.Minute.ToString () + DateTime.Now.Second.ToString () + DateTime.Now.Millisecond.ToString ();
Get the physical path to the site
string uploadfilepath = null;
If true, creates a folder at the current time, otherwise the folder that is set
if (creatdirectory)
{
Uploadfilepath = System.Web.HttpContext.Current.Server.MapPath (".") + @ "\" + DateTime.Now.Year.ToString () + DateTime.Now.Month.ToString () + DateTime.Now.Day.ToString () + @ "\";
}
Else
{
Uploadfilepath = System.Web.HttpContext.Current.Server.MapPath (".") + path;
}
Get the path to the file upload
String Sourcepath=name. Value.trim ();
Determine if the upload file is empty
if (SourcePath = = "" | | SourcePath = null)
{
Message ("You did not upload the data ah, is not a mistake ah!");
return null;
}
Get file name extension
String tfiletype = Sourcepath.substring (Sourcepath.lastindexof (".") +1);
Get the size of the uploaded file
Long StrLen = name. Postedfile.contentlength;
Decompose the format that allows uploading files
string[] temp = filetype.split (' | ');
To set whether the uploaded file is a permitted format
BOOL flag = FALSE;
Determine the size of the uploaded file
if (StrLen >= sizes)
{

Message ("Upload the picture can not be greater than" + sizes + "KB");
return null;
}
To determine if the uploaded file is a permitted format
foreach (string data in temp)
{
if (data = = Tfiletype)
{
Flag = true;
Break
}
}
If upload is true, it is not allowed to upload for false
if (!flag)
{
Message ("The current system supports the format is:" +filetype);
return null;
}
System.IO.DirectoryInfo dir=new System.IO.DirectoryInfo (Uploadfilepath);
To determine if a folder exists and does not exist, create
if (!dir. Exists)
{
Dir. Create ();
}
FilePath = Uploadfilepath + Modifyfilename + "." + Tfiletype;
Name. Postedfile.saveas (FilePath);
FilePath = path + Modifyfilename + "." + Tfiletype;

return filePath;

}
Catch
{
Abnormal
Message ("An unknown error occurred!") ");
return null;
}
}

private void Message (String msg,string URL)
{
System.Web.HttpContext.Current.Response.Write ("Alert (' +msg+"); window.location= ' "+url+" ");
}

private void Message (String msg)
{
System.Web.HttpContext.Current.Response.Write ("alert (' +msg+ ');");
}
}
}



--------------------------------------------------------------------------------


If winter comes, can spring be far behind?
I still believe, some day and me.



--------------------------------------------------------------------------------

1. C # Implementation of Web 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.

So how do you use C # to implement file upload functions? 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&nbsp;id=uploadfile1&nbsp; type=file&nbsp; size=49&nbsp; runat= "SERVER" so that it becomes a server-side control, and 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:

<form method=post enctype=multipart/form-data runat= "Server" >
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:

Upload a picture of the program section
DateTime now = DateTime.Now;
Take the current time to the object in 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 (uploadfile1. Postedfile.contentlength!= 0)//Determine if the selection dialog box chooses a file length of 0
{
Uploadfile1. Postedfile.saveas (Strbaselocation+now. Dayofyear.tostring () +uploadfile1. PostedFile.ContentLength.ToString () + ". jpg");
Perform 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 () +uploadfile1. 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 () +uploadfile1. 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

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 functional module for player contributors to implement the corresponding functions used in the upload file function.
</summary>
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)//main function to implement 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 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 > 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.