asp.net super Large File upload method

Source: Internet
Author: User
Tags datetime file upload

ASP tutorial. NET Super Large File Upload method

asp.net tutorial Large file upload is an imperfect and flawed field that is believed to be improved and developed in the near future if you have solved it by stating that you are in a good company, otherwise you may consider using a third-party product to resolve it. File upload problem, we can find a lot of different ways to solve the challenge is to find out the pros and cons of different practices and find a solution for their own projects, this is not only in the file upload this aspect!

<asp:image id= "Imglogo" runat= "Server"/><br/>
<asp:label id= "labmsg" runat= "Server" forecolor= "#cc0000" ></asp:label><br/>
<asp:fileupload id= "Uploadlogo" runat= "Server" width= "60%" height= "22px"/> &nbsp;&nbsp;
<asp:button id= "Btnupload" runat= "server" text= "upload"
onclick= "Btnupload_click"/>

Aspx.cs page

Upload button

protected void Btnupload_click (object sender, EventArgs e)
{
UploadFile uploadfileobj = new UploadFile (); Instantiate file Upload class
uploadfileobj.maxfilesize = 100; Set maximum length of upload file, Unit K
Uploadfileobj.filetype = "Jpg|jpeg|gif|png"; Set file types to allow uploading

String uploadpath = Server.MapPath ("~/uploadfiles/other/"); Set upload directory full path
Uploadfileobj. Uploadfilego (Uploadpath, Uploadlogo); File Upload
Labmsg.text = Uploadfileobj.uploadinfo; Upload message prompt
if (uploadfileobj.uploadstate = = True)
{
Imglogo.imageurl = "~/uploadfiles/other/" + uploadfileobj.newfilename; Show pictures
}

}

Uploadfile.cs File Upload Class

using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.web.ui.webcontrols.webparts;
Using System.Web.UI.HtmlControls;
Using System.IO;

Namespace common
{
<summary> File Upload class </summary>
public class UploadFile
{

#region Field

private string _uploadinfo; Return information for file uploads.
private bool _uploadstate; The return status of the file upload.
private string _filetype; The type of file that is allowed to upload.
private int _filesize; Size of uploaded file, Unit b
private int _maxfilesize; Upload file size maximum length, Unit b
private string _newfilename; The file name after the upload.

#endregion

<summary> Initial File Upload class (default) </summary>
Public UploadFile ()
{
_uploadinfo = "None";
_uploadstate = false;
_filetype = "*";
_maxfilesize = 1024000;//1000k is 1024*1000b, Unit B
_newfilename = "";
}

#region Properties
<summary> File upload return information </summary>
public string Uploadinfo
{
set {_uploadinfo = value;}
get {return _uploadinfo;}
}

<summary> file Upload return status, success true, Failure false</summary>
public bool Uploadstate
{
set {_uploadstate = value;}
get {return _uploadstate;}
}

<summary> allow the type of upload file, * The default representative can be any type, or custom type, such as "Jpg|gif|bmp" </summary>
public string filetype
{
set {_filetype = value;}
get {return _filetype;}
}

<summary> Upload file size, Unit k</summary>
public int FileSize
{
get {return _filesize/1024;}
}

<summary> maximum length of uploaded file size, Unit k</summary>
public int MaxFileSize
{
set {_maxfilesize = value * 1024;}
get {return _maxfilesize/1024;}
}

<summary> file name after uploading </summary>
public string NewFileName
{
set {_newfilename = value;}
get {return _newfilename;}
}

#endregion


#region Upload the main program
<summary> uploading local files to server </summary>
<param name= "Strsavedir" > The physical path saved on the server side. </param>
<param name= "Fileuploadctrlid" > uploaded file objects, where the FileUpload controls are used,</param>
<param> second argument if the HTML input (file) control can be changed to: HtmlInputFile htmctrlobjuploadfile</param>
<returns></returns>
public void Uploadfilego (string strsavedir, FileUpload fileuploadctrlid)
{
int intfileextpoint = Fileuploadctrlid.postedfile.filename.lastindexof ("."); The last one. Position of the number
String strfileextname = fileuploadctrlid.postedfile.filename.substring (Intfileextpoint + 1). ToLower (); Gets the suffix name of the uploaded file.

_filesize = fileuploadctrlid.postedfile.contentlength;//uploaded file size byte

            if (_filesize = 0)//Determine if any files need to be uploaded or if the selected file is 0 bytes.
            {
                 _uploadinfo = "No files selected to upload or selected file size is 0 bytes";
                _uploadstate = False
                return;// Returns the file upload status and information.
           }

if (_filesize > _maxfilesize)//Limit the file size (byte) to be uploaded.
{
_uploadinfo = "The uploaded file exceeds the limit size (" + (_maxfilesize/1024). ToString () + "K");
_uploadstate = false;
Return Returns the file upload status and information.
}

if (_filetype!= "*")
{
if (_filetype.tolower (). indexof (Strfileextname.tolower (). Trim ()) = = 1)//Determine whether the file type to be uploaded is within the allowable range.
{
_uploadinfo = "File type not allowed to upload (Allowed type: |" + _filetype + ")";
_uploadstate = false;
Return Return file upload status and information
}
}

if (_newfilename = "")
{
DateTime dtenow = DateTime.Now; Defines a date object that is named after the uploaded file.
_newfilename = dtenow.year.tostring () + dtenow.month.tostring () + dtenow.day.tostring () + GETRANDOMSTR (8); Randomly named after the uploaded file, date + random number.
_newfilename = _newfilename + "." + Strfileextname; File name that contains the extension
}
Fileuploadctrlid.postedfile.saveas (This.getsavedirectory (strsavedir) + _newfilename); Save the uploaded file with the new file name to the specified physical path.
_uploadinfo = "File upload success"; Returns the physical path of the server-side file after the upload.
_uploadstate = true;

}
#endregion

<summary> get random numbers for a specified number of digits </summary>
<param name= "Rndnumcount" > number of random digits. </param>
<returns></returns>
private string getrandomstr (int rndnumcount)
{
String Randomstr;
Randomstr = "";
Random rnd = new Random ();
for (int i = 1; I <= rndnumcount; i++)
{
Randomstr + + rnd.next (0, 9). ToString ();
}
return randomstr;
}


<summary> Get upload file storage directory </summary>
<param name= "DirectoryPath" The physical path of the file. </param>
<returns> returns the directory where the file is stored. </returns>
public string Getsavedirectory (string directorypath)
{
if (!directory.exists (DirectoryPath))//Determine if the current directory exists.
{
Directory.CreateDirectory (DirectoryPath); Set up the upload file storage directory.
}
return directorypath;
}

}

#region attached: Modify upload size configuration
/*
What needs to be modified is
In the C:windowsmicrosoft.netframeworkv1.1.4322config catalogue,
File maxrequestlength= "4096" found
Change the value a bit larger, for example: 102400
The unit of this parameter should be kb

The above method is to modify the global, if the public need to modify a project, then modify the project Web.config file

Add between <system.web></system.web>,
which
maxRequestLength: Set the maximum size of the uploaded file, in kilobytes: KB. (The default is 4096kb, or 4m)
Executiontimeout: Set timeout time, in seconds. (default is 90 seconds)
*/
#endregion
}

Neatupload intercepts the current HttpWorkerRequest object in the BeginRequest event of the ASP.net pipeline, and then directly calls its readentitybody to get the data stream passed by the client. and analyzed and dealt with. And to get the status of the current upload by polling with the new request. An introduction to Neatupload and other open source components can refer to Jeffreyzhao's upload file in asp.net application, and of course he also said Memba Velodoc XP Edition and SWFUpload

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.