Several common methods, the main contents of this article include:
First part: First of all, let's take a look at how to solve the file upload size limit in ASP, we know that by default, the file upload size limit is 2M, we can generally 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 restrict the format of the uploaded file (app. config) 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 upload the file to call this method, the returned file information is saved to the database, as for the download, directly open the path is 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, add: <add verb= "*" path= "openfile.aspx" type= "RuixinOA.Web.BaseClass.OpenFile, Ruixinoa.web" in Web. config/> 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, the implementation of the following:
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
{
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.
C # large File upload (go--to be verified)