asp.net (C #) upload large files in several common application methods _ practical skills

Source: Internet
Author: User
Tags datetime httpcontext save file string format
Several common methods, the main contents of this article include:
  
Part I: First of all, 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 change Web.config file to customize the maximum file size, as follows:

The maximum size of the uploaded file becomes 4M, but this does not allow us to extend the maxRequestLength value 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 in chunks from the pipe created by IIS for asp.net. 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 describe 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 ()
{}
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 in the configuration file (app.config):
? XML version= "1.0" encoding= "gb2312"?>
<application>
<fileupload>
<format>.jpg|. Gif|. Png|. Bmp
</fileupload>
</application> so we can start to write our upload file method, as follows: Public FileUpload UploadFile (HtmlInputFile inputfile,string FilePath, String Myfilename,bool israndom)
{
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 Three: 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 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;

Namespace RuixinOA.Web.BaseClass
{
public class Openfile:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
Retrieve 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 reference System.Net this 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.
Related Article

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.