Asp. NET file upload and download __.net

Source: Internet
Author: User
Tags rar urlencode

aspx page

<%@ Page language= "C #" autoeventwireup= "true" codefile= "upload and download files. Aspx.cs" inherits= "Upload and download files"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
">  

aspx background code:

Using System;
Using System.Collections;
Using System.Configuration;
Using System.Data;
Using System.Linq;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.HtmlControls;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Xml.Linq;

Using System.IO;
    public partial class upload and download files: System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {} protected void btnAdd_Click (object sender, EventArgs e) {//file formerly known as String fileName = Path.getfilenam
        E (this.homeworkFile.FileName); File New name = File Formerly known + current time string newfilename = filename.substring (0, Filename.indexof ('. ')) + DateTime.Now.ToString ("Yyyym
        Mddhhmmss ");
        Add a suffix to the filename newfilename + = filename.substring (Filename.indexof ('. '), Filename.length-filename.indexof ('. ')); Get File Store path name string Url = configurationmanager.appsettings["Resoursepath"] + configurationmanager.appsettings ["ReshomeWorkcontentpath "] + @" + "+ newfilename; Verify file Size if (this. Isfilesizelessmax ()) {//Verify file type if (This.istypeok (URL)) {//Verify that the path to the file store is saved In string pathstr = configurationmanager.appsettings["Resoursepath"] + configurationmanager.appsettings["RE
                Shomeworkcontentpath "]; if (!    Directory.Exists (PATHSTR))//If the path {directory.createdirectory (PATHSTR) does not exist; Create path} if (!
                    Url.equals (""))//If there is upload file {fileupload fileupload = new FileUpload ();
                    1. deposit File//Fileupload.saveas (URL);
                HomeworkFile.PostedFile.SaveAs (URL); ///<summary>///Verify that the upload file exceeds the specified maximum value///</summary>///<retu rns></returns> private bool Isfilesizelessmax () {//return value BOOL REsult = false; if (this.homeworkFile.HasFile)//If uploaded file {//Get the maximum allowable value of uploaded file long filemaxsize = 1024 * 102
            4; try {filemaxsize *= int. Parse (configurationmanager.appsettings["Fileuploadmaxsize"). Substring (0, configurationmanager.appsettings["fileuploadmaxsize").
            LENGTH-1)); The catch (Exception ex) {//this.
            WriteException ("Userpotal:homework", ex); } if (This.homeworkFile.PostedFile.ContentLength > int. Parse (filemaxsize.tostring ())//If the file size exceeds the specified maximum value of {//this. ShowMessage ("file exceeds the specified size.")
            ");
            else {result = true;
        else//If no uploaded file {result = true;
    return result;
///<summary>///Methods for validating file types///</summary>///<param name= "FileName" ></param>    <returns></returns> private bool Istypeok (string fileName) {//return result bool Endre
        Sult = false;
        validation results int result = 0;
            if (!filename.equals (""))//If there is upload file {//allowed file type string[] FileType = null; try {fileType = configurationmanager.appsettings["FileType"].
            Split (', '); The catch (Exception ex) {//this.
                ShowMessage ("Get configuration file Information error"); This.
            WriteException ("Adminprotal:homework", ex);
            FileName = filename.substring (Filename.lastindexof ('. '), Filename.length-filename.lastindexof ('. ')); for (int i = 0; i < filetype.length i++) {if (filetype[i).
                Equals (FileName))//If the legal file type {result++; } if (Result > 0) {endresult= true;
        else//If no upload file {Endresult = true;
    return endresult; ///download method one protected void Btndownfile_click (object sender, EventArgs e) {/* Microsoft provides a new method for the response object Tran Smitfile to troubleshoot problems that cause Aspnet_wp.exe process recycling when downloading more than 400mb of files using Response.BinaryWrite.
        Code as follows: * * Response.ContentType = "application/x-zip-compressed";
        Response.AddHeader ("Content-disposition", "attachment;filename=dbintegrate20120521030107.txt");
        string filename = Server.MapPath ("Bjnetwork/data/dbintegrate20120521030107.txt");
    Response.TransmitFile (filename); ///download method two protected void Btndownfilebywritefile_click (object sender, EventArgs e) {/* using System.IO ; */String filename = "DBintegrate20120521030107.txt";//client-saved filename string filePath = Server.MapPath ("BJNETW
    Ork/data/dbintegrate20120521030107.txt ");//path FileInfo FileInfo = new FileInfo (FilePath);    Response.Clear ();
        Response.clearcontent ();
        Response.ClearHeaders ();
        Response.AddHeader ("Content-disposition", "attachment;filename=" + filename);
        Response.AddHeader ("Content-length", fileInfo.Length.ToString ());
        Response.AddHeader ("content-transfer-encoding", "binary");
        Response.ContentType = "Application/octet-stream";
        response.contentencoding = System.Text.Encoding.GetEncoding ("gb2312");
        Response.WriteFile (Fileinfo.fullname);
        Response.Flush ();

    Response.End ();  ///download method three protected void Btndownfilebywritefile2_click (object sender, EventArgs e) {string fileName = "Front desk teacher and student Interface 20120521034329.rar";//client saved file name string FilePath = Server.MapPath ("bjnetwork/data/foreground teacher and student interface contrast 20120521
        034329.rar ");//path System.IO.FileInfo FileInfo = new System.IO.FileInfo (FilePath); if (fileinfo.exists = = true) {Const long chunksize = 102400;//100k reads the file every time and reads only 100K, this can alleviate the pressure of the server byte[] buffer = new Byte[chunksize];
            Response.Clear ();
            System.IO.FileStream IStream = System.IO.File.OpenRead (FilePath);
            Long Datalengthtoread = istream.length;//Gets the total size of the downloaded file Response.ContentType = "Application/octet-stream"; Response.AddHeader ("Content-disposition", "attachment;
            Filename= "+ httputility.urlencode (fileName)); while (Datalengthtoread > 0 && response.isclientconnected) {int lengthread = Istre Am. 
                Read (buffer, 0, Convert.ToInt32 (chunksize));//Read the size Response.OutputStream.Write (buffer, 0, lengthread);
                Response.Flush ();
            Datalengthtoread = Datalengthtoread-lengthread;
        } response.close (); ///download method four protected void Btndownfilebystream_click (object sender, EventArgs e) {string Filenam E = "Foreground teacher and student interface 20120521034329.rar";//client saved filename string Filepath = Server.MapPath ("bjnetwork/data/front desk teacher and student Interface 20120521034329.rar");//path////The file is downloaded as a stream of characters FileStream fs = new Filest
        Ream (FilePath, FileMode.Open); byte[] bytes = new byte[(int) fs.
        Length]; Fs. Read (bytes, 0, bytes.
        Length); Fs.
        Close ();
        Response.ContentType = "Application/octet-stream"; Notifies the browser to download the file instead of opening Response.AddHeader ("Content-disposition", "attachment;
        Filename= "+ httputility.urlencode (FileName, System.Text.Encoding.UTF8));
        Response.BinaryWrite (bytes);
        Response.Flush ();
    Response.End (); }
}


Web configuration file:

<appSettings>
<!--the path to upload file-->
<add key= "Resoursepath" value= "D:\IbeaconShow\BJNetwork"/>
<add key= "Reshomeworkcontentpath" value= "\data"/>
<!--the size of the--> file can be uploaded
<add key= "fileuploadmaxsize" value= "20M"/>
<!--can upload file types-->
<add key= "FileType" value= "Zip,.txt,.doc,.rar,.xls,.rtf,.xlsx,.docx,.png"/>
</appSettings>

<system.web>
<!--modify the asp.net default upload file size-->

</system.web>

Modification of upload size in IIS

1, first of all, to the process of the IIS service off, that is, the Inetinfo.exe process off, or the documents inside do not give you change yo ~ ~ ~
2, found in the system directory: Windows/system32/inesrv/metabase.xml "file, find a text editor to open him, I use editpuls (this guy is good, with font color), ctrl+f Find the Aspmaxrequestentityallowed= "204800", this is the default size of the IIS upload file, the default is 204800Byte, that is, 200KB, change it to the size you need it.


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.