Asp.net| Collection | upload | download | chinese
The uploading and downloading of files is a technique that we often need to use in the actual project development process, here are some common methods.
File upload is our actual project development process often need to use the technology, here are several common methods, the main contents of this article include:
1, how to solve the file upload size limit
2. Save to server in file form
3. Convert to binary byte stream save to database and download method
4, upload resources on the Internet
The first part:
First, let's say how to solve the problem of file upload size limit in asp.net, we know that by default asp.net file upload size is limited to 2M, in general, we can use the change Web.config file to customize the maximum file size, 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 II:
Here's how to upload a file from a client to the server and return some basic information about the uploaded file.
First we define a class that stores the information for the uploaded file (required to return).
public class FileUpload
{
Public FileUpload ()
{}
/**////<summary>
Upload file name
</summary>
public string FileName
{
Get
{
return fileName;
}
Set
{
FileName = value;
}
}
private string FileName;
/**////<summary>
Upload file path
</summary>
public string FilePath
{
Get
{
return filepath;
}
Set
{
filepath = value;
}
}
private string filepath;
/**////<summary>
File name extension
</summary>
public string FileExtension
{
Get
{
return fileextension;
}
Set
{
FileExtension = value;
}
}
private string fileextension;
}
In addition, we can restrict the format of the uploaded file in the configuration file (app.config):
<?xml version= "1.0" encoding= "gb2312"?>
<Application>
<FileUpLoad>
<format>.jpg|. Gif|. Png|. Bmp</format>
</FileUpLoad>
</Application>
So we can start writing the way we upload files, as follows:
Public FileUpload UploadFile (htmlinputfile inputfile,string filepath,string myfilename,bool)
{
FileUpload fp = new FileUpload ();
String filename,fileextension;
String Savename;
//
Create an uploaded 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 met
//
if (format. IndexOf (fileextension) ==-1)
{
throw new ApplicationException ("Upload data format is not valid");
}
//
Generate random file names 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);
To determine if a path exists, 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 on uploaded files
return FP;
}
Then we upload the file when we can call this method, the return of the file information saved to the database, as for downloading, directly open that path on the OK.
Part III:
Here we mainly say how to upload files in binary form and download. First say upload, the following methods:
Public byte[] UploadFile (HtmlInputFile f_ifile)
{
Get access to uploaded files specified by the client
Httppostedfile Upfile=f_ifile.postedfile;
Get the length of the uploaded file
int upfilelength=upfile.contentlength;
Get 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 the 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 out on it, in fact, this method is not desirable, In the actual application may appear can not open a site error, I generally use the following method:
First, add 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 method that executes the RuixinOA.Web.BaseClass.OpenFile class, which is implemented 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;
Summary description of the
namespace RuixinOA.Web.BaseClass
{
/**////<summary>
///netufile.
///</summary>
public class Openfile:ihttphandler
{
public void ProcessRequest (HttpContext conte XT)
{
//Remove the file information 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;}
}
}
}
When the above method is executed, the user is prompted to choose whether to open or download directly. That's the part we're talking about here.
Part IV:
This section mainly says how to upload a resource on the Internet to the server.
First you need to refer to the System.Net namespace, and then do the following:
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 it's a good solution to this problem.
Part V: summary
Today, a simple introduction of several file upload and download methods, are in the actual project development often need to use, there may be imperfect places, I hope you can exchange the experience of the project development