Asp. File upload and download methods commonly used in net

Source: Internet
Author: User
Tags date bool comments file size file upload httpcontext string format tostring
asp.net| Upload | download

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

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 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;
           
            //
           //Set up 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 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);


           //Determine if the 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;

Namespace RuixinOA.Web.BaseClass
{
   /**////<summary>
   /// Summary description of the netufile.
   ///</summary>
    public class Openfile:ihttphandler
     {
        public void ProcessRequest (HttpContext context)
        {
            
           /Remove file information from the database for download
             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. We have an article in detail about how to use it, and I'm not going to say much about it here.
Please refer to: Convert the dynamic page into binary byte stream

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. Write a bad place, please correct me, thank you!

Email:pwei013@163.com
Posted on 2006-05-24 22:48 SHY520 Read (3256) Comments (17) Edit collection references to 365Key categories: asp.net1.1

Comments:
# re:asp. NET file upload Download Method collection 2006-05-25 09:54 | Ivan

Not bad.  Especially the third part of the download, especially thanks. Reply

# re:asp. NET file upload Download Method collection 2006-05-25 10:19 | Meditation has passed

Learn
Reply

# re:asp. NET file upload Download Method collection 2006-05-25 10:26 | Iamsunrise

This is also called a set, pulled. Reply

# re:asp. NET file upload Download Method collection 2006-05-25 10:31 | Onekey

Thank you, I wrote it very useful reply

# re:asp. NET file upload Download Method collection 2006-05-25 10:35 | SHY520

@Ivan, meditation has passed, Onekey
You're welcome, there are imperfections, and I will add
Reply

# re:asp. NET in common file upload download method 2006-05-25 10:39 | SHY520

@iamsunrise
Thanks for reminding, the name has been changed,:) Reply

# re:asp. NET in common file upload download method 2006-05-25 11:06 | Tianjj

Can you elaborate on how it works: implied HttpWorkerRequest
And when you upload, how to relate.
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)
{
..
}
} reply

# re:asp. NET in common file upload download method 2006-05-25 11:14 | SHY520

@tianjj
I usually modify the configuration file to upload the file size, basically enough.
This method of concrete I have not tried, go back to study, then sent up.  :-) Reply

# re:asp. NET in common file upload download method 2006-05-25 11:18 | Fuyude.net

@tianjj
This is actually a HttpHandler module. Reply

# re:asp. NET in common file upload download method 2006-05-25 11:20 | SHY520

@fuyude. Net
Oh, thanks for reminding me of the reply

# re:asp. NET in common file upload download method 2006-06-06 00:32 | Htusoft

Entitydata data = os. Getfiledetail (ID);
What method does ID use to communicate in?
Reply

# re:asp. NET in common file upload download method 2006-06-06 08:36 | SHY520

@htusoft
This sentence is just to get the details of the file to download, you can replace your own method, examples in the WEBSHARP framework reply

# re:asp. NET in common file upload download method 2006-07-08 18:01 | Htusoft

I just want to know if I take a parameter openfile.aspx? ID=0001,
How to pass this parameter to OpenFile class, can you use querystring?
It shouldn't be, because the OpenFile class does not inherit from the Openfile.aspx page base class. Reply

# re:asp. NET in common file upload download method 2006-07-08 19:52 | SHY521

@htusoft
You can use QueryString to return the value

# re:asp. NET in common file upload download method 2006-07-08 19:54 | SHY521

But my OpenFile class is inherited from IHttpHandler, so I can reply.

# re:asp. NET in common file upload download method 2006-07-08 22:00 | Htusoft

This will also display a openfile.aspx page. Can you not let it show a reply

# re:asp. NET in common file upload download method 2006-07-09 15:34 | SHY520

@htusoft
This I don't know, this should be a better way to reply



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.