Asp. NET uploading files in several ways

Source: Internet
Author: User
Tags httpcontext save file

Uploading a file instance

if (filedealer.hasfile)//Determine if the file exists
{
string filepath = "";
Try
{
string path = Filedealer.filename;
string filename = path. Split ('. ') [0] + "_" + DateTime.Now.ToString ("Yyyymmddhhmmss");//Duplicate name
if (FileDealer.PostedFile.ContentLength > 50 * 1024 * 1024)
{
Page.ClientScript.RegisterStartupScript (GetType (), "", "<script>alert (' upload file cannot exceed 50m! '); </script> ");
Return
}
String serverpath = @ "~/files/activty/";//store path
String fileextente = Path.getextension (filedealer.filename);//Extension
if (! Directory.Exists (Server.MapPath (Serverpath)))
{
Directory.CreateDirectory (Server.MapPath (Serverpath));
}
filepath = Path.Combine (serverpath, filename + fileextente);
Filedealer.saveas (Server.MapPath (filepath));
Obj. Attachment = filepath;
}
catch (Exception ex)
{
Throw ex;
}

}

Find a lot of information, learned a lot of useful things, the simplest implementation is to use the FileUpload control. Using System;namespace upfile {//
A summary description of the upfile.
///
public class Upfile
{
private string path = null;
private string fileType = null;
private int sizes = 0;
///
Initialize variables
///
Public Upfile ()
{
Path = @ "\uploadimages\"; Upload path
FileType = "Jpg|gif|bmp";
sizes = 200; File size, default 200KB
}///
Set 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 image
///
Upload Control Name
True to create the folder at the current time, false to set the 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 create a folder name 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 sets the folder
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 file's upload path
String Sourcepath=name. Value.trim ();
Determine if the upload file is empty
if (SourcePath = = "" | | SourcePath = = null)
{
Message ("You did not upload data ah, is not mistaken!");
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;
Decomposition allows file format to be uploaded
string[] temp = filetype.split (' | ');
Set whether the uploaded file is in the allowed format
BOOL flag = FALSE;
Determine the upload file size
if (StrLen >= sizes)
{

Message ("The uploaded picture cannot be greater than" + sizes + "KB");
return null;
}
Determine if the uploaded file is in the allowed format
foreach (string data in temp)
{
if (data = = Tfiletype)
{
Flag = true;
Break
}
}
If the upload is true, the upload is not allowed for false
if (!flag)
{
Message ("The current format supported by this system is:" +filetype);
return null;
}
System.IO.DirectoryInfo dir=new System.IO.DirectoryInfo (Uploadfilepath);
Determines whether a folder exists, does not exist, or creates
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 has 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+ "');");
}
}
}--------------------------------------------------------------------------------
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. However, the control is not yet a service-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 service-side control, if you need to upload several files simultaneously, we can add this control accordingly. It is important to note that the <form> property 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 of the program section
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 where the files will be uploaded to the server
if (uploadfile1. Postedfile.contentlength! = 0)//Determine if the file length selected by the Select dialog box is 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 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 large;  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 (); Gets 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 non-repeating 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;
}
}
}
Asp. NET file upload Download method collection File Upload download is our actual project development process often need to use the technology, here are a few common methods, the main content of this article includes: 1, how to solve the file upload size limit 2, file format saved to server 3,  Convert to binary byte stream save to database and download method 4, upload resources on the Internet the first part:  First of all, let's take a look at how to solve the file upload size limit in ASP. net file upload size limit to 2M, in general, we can change the Web. config file to customize the maximum file size, as follows: The maximum value of the uploaded file becomes 4M, but this does not allow us to enlarge the value of maxRequestLength indefinitely, because ASP. NET will load all the files into memory and then process them. The solution is to use the implied httpworkerrequest, using its getpreloadedentitybody and Readentitybody methods to read data from the pipe block built by IIS for ASP. The implementation method is as follows: Iserviceproviderprovider= (IServiceProvider) httpcontext.current;
Httpworkerrequestwr= (HttpWorkerRequest) provider. GetService (typeof (HttpWorkerRequest));
Byte[]bs=wr. Getpreloadedentitybody ();
.
if (!WR. Isentireentitybodyispreloaded ())
{
intn=1024;
Byte[]bs2=newbyte[n];
while (WR. Readentitybody (bs2,n) >0)
{
..
}
This will solve the problem of uploading large files.  Part Two: Let's show you how to upload a file from a client to the server and return some basic information about the file. First we define a class that stores the information for the uploaded file (as needed on return). public class FileUpLoad
{
Public FileUpLoad ()
{}
/**////
Upload file name
///
public string FileName
{
Get
{
return fileName;
}
Set
{
FileName = value;
}
}
private string FileName; /**////
Upload file path
///
public string FilePath
{
Get
{
return filepath;
}
Set
{
filepath = value;
}
}
private string filepath; /**////
File name extension
///
public string FileExtension
{
Get
{
return fileextension;
}
Set
{
FileExtension = value;
}
}
private string fileextension;
In addition, we can also restrict the format (app. config) of the uploaded file in the configuration file: XML version= "1.0" encoding= "gb2312"?>
<application>
<fileupload>
<format>.jpg|. Gif|. Png|. Bmp
</fileupload>
</application> so that we can begin to write our method of uploading the file, as follows: Public FileUpLoad uploadfile (HtmlInputFile inputfile,string FilePath, String Myfilename,bool israndom)
{
FileUpLoad fp = new FileUpLoad ();
String filename,fileextension;
String Savename; //
Set up an Upload object
//
Httppostedfile postedFile = inputfile.postedfile; FileName = System.IO.Path.GetFileName (postedfile.filename);
FileExtension = System.IO.Path.GetExtension (fileName); //
Determine file format based on type
//
AppConfig app = new AppConfig ();
string format = App. GetPath ("Fileupload/format"); //
Returns if the format is not compliant
//
if (format. IndexOf (fileextension) ==-1)
{
throw new ApplicationException ("Invalid upload data format");
} //
Generate random filenames based on date and random numbers
//
if (myfilename! = string. Empty)
{
FileName = myFileName;
} if (Israndom)
{
Random Objrand = new Random ();
System.DateTime date = DateTime.Now;
Generate Random file names
Savename = date. Year.tostring () + date. Month.tostring () + date. Day.tostring () + date. Hour.tostring () + date. Minute.tostring () + date. Second.tostring () + convert.tostring (Objrand.next (99) *97 + 100);
FileName = Savename + fileextension;
} String phypath = HttpContext.Current.Request.MapPath (FilePath); Determine if the path exists and create a path if it does not exist
DirectoryInfo Updir = new DirectoryInfo (Phypath);
if (!updir.exists)
{
Updir.create ();
} //
Save File
//
Try
{
Postedfile.saveas (Phypath + fileName); Fp. FilePath = FilePath + fileName;
Fp. FileExtension = fileextension;
Fp. filename = filename;
}
Catch
{
throw new ApplicationException ("Upload failed!");
}//Return information for uploading files
return FP;
Then we can call this method when uploading the file, save the returned file information to the database, and as for the download, open the path directly to OK. Part III: Here we mainly talk about how to upload files in binary format and download. First say upload, the method is as follows: public byte[] UploadFile (HtmlInputFile f_ifile)
{
Gets access to the uploaded file specified by the client
Httppostedfile Upfile=f_ifile.postedfile;
Get the length of the uploaded file
int upfilelength=upfile.contentlength;
Gets the client MIME type of the uploaded file
string contentType = Upfile.contenttype;
Byte[] Filearray=new byte[upfilelength]; Stream Filestream=upfile.inputstream; FileStream.Read (filearray,0,upfilelength);
return filearray;
This method returns the binary byte stream of the uploaded file, so that we can save it to the database. Here is a download of this form, perhaps you will think of this way to download is to create a new ASPX page, and then in its Page_Load () event to take out the binary byte stream, and then read it out, in fact, this method is not advisable, In the actual application may be unable to open a site error, I generally use the following method: First, in the Web. config: <add verb= "*" path= "openfile.aspx" type= "  RuixinOA.Web.BaseClass.OpenFile, Ruixinoa.web "/> This means that when I open openfile.aspx this page, the system will automatically go to the implementation of RuixinOA.Web.BaseClass.OpenFile in this class method, the implementation is as follows: using System;
Using System.Data;
Using System.Web;
Using System.IO;
Using Ruixin.workflowdb;
Using Rxsuite.base;
Using Rxsuite.component;
Using Ruixinoa.businessfacade;namespace RuixinOA.Web.BaseClass
{
/**////
A summary description of the netufile.
///
public class Openfile:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
Remove the file information you want to download from the database
RuixinOA.BusinessFacade.RX_OA_FileManager OS = new Rx_oa_filemanager ();
Entitydata data = os.   Getfiledetail (ID); if (data! = NULL && data. tables["Rx_oa_file"]. Rows.Count >0)
{
DataRow dr = (DataRow) data. tables["Rx_oa_file"]. Rows[0];
Context. Response.Buffer = true;
Context. Response.Clear ();
Context. Response.ContentType = dr["Ccontenttype"]. ToString ();
Context. Response.AddHeader ("Content-disposition", "attachment;filename=" + httputility.urlencode (dr["CTitle"]. ToString ()));
Context. Response.BinaryWrite ((byte[]) dr["ccontent"]);
Context. Response.Flush ();
Context. Response.End ();
}
}
public bool IsReusable
{
get {return true;}
}
}
After executing the above method, the user is prompted to choose whether to open or download directly.  That's what we're talking about here.  Part IV: This section mainly says how to upload a resource on the Internet to the server. You first need to refer to the System.Net namespace, and then proceed as follows: HttpWebRequest HWQ = (HttpWebRequest) webrequest.create ("http://localhost/pwtest/ WebForm1.aspx ");
HttpWebResponse HWR = (httpwebresponse) hwq. GetResponse ();
byte[] bytes = new BYTE[HWR. ContentLength];
Stream stream = Hwr. GetResponseStream ();
Stream. Read (Bytes,0,convert.toint32 (HWR. ContentLength));
HttpContext.Current.Response.BinaryWrite (bytes);  HttpWebRequest can read files from the Internet, so this problem can be solved well. Part V: Summary of the simple introduction of several file upload and download methods, are in the actual project development often need to use, there may be imperfect place, I hope you can communicate with each other on the project development experience.

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.