Set of methods for uploading and downloading files in ASP. NET

Source: Internet
Author: User
This article summarizes some methods for uploading and downloading files in ASP. NET. File upload and download in ASP. NET is a frequently used technology. File Upload/download is a technology that we often use in the actual project development process. Several common methods are provided here. The main content of this article includes: 1. How to Solve the file upload size limit 2. Save the file to the server 3. convert it into a binary byte stream and save it to the database and download method 4. Upload Internet resources ASP.. NET file upload and download. Part 1: First, let's talk about how to solve the file upload size limit in asp.net. We know that the file upload size limit of asp.net is 2 MB by default, in general, we can change the Web. the Config file is used to customize the maximum file size. The maximum size of the uploaded file is 4 MB, but this does not allow us to infinitely expand the value of MaxRequestLength, because asp.net loads all files into the memory and then processes them. The solution is to use the implicit HttpWorkerRequest and its GetPreloadedEntityBody and ReadEntityBody methods to read data from the pipe created by IIS for asp.net in blocks. Implementation Method: 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 solves the problem of uploading large files. ASP. NET file upload and download. Part 2: Next we will introduce how to upload a client file to the server in the form of a file and return some basic information about the uploaded file. First, we define a class to store the information of the uploaded file (required when returned ). Public class FileUpLoad {public FileUpLoad () {}/ *** // upload the 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 extension // public string FileExtension {get {return fileExtension;} set {fileExtensio N = 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> to start writing the File Upload 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 upload object // HttpPostedFile postedFile = InputFile. postedFile; fileName = System. IO. path. getFileName (po StedFile. fileName); fileExtension = System. IO. path. getExtension (fileName); // determine the file format based on the Type // AppConfig app = new AppConfig (); string format = app. getPath ("FileUpLoad/Format"); // if the format does not match, return // if (Format. indexOf (fileExtension) =-1) {throw new ApplicationException ("the format of uploaded data is invalid ");} //// generate a random file name based on the date and random number. // if (myfileName! = String. empty) {fileName = myfileName;} if (isRandom) {Random objRand = new Random (); System. dateTime date = DateTime. now; // generate the random file name 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); // determines whether the path exists. if not, create the path DirectoryInfo upDir = new DirectoryInfo (phyPath); if (! UpDir. exists) {upDir. create ();} // save the file // try {postedFile. saveAs (phyPath + fileName); fp. filePath = filePath + fileName; fp. fileExtension = fileExtension; fp. fileName = fileName;} catch {throw new ApplicationException ("Upload Failed! ");} // Return the information of the uploaded file return fp;} Then we can call this method when uploading the file and save the returned file information to the database, as for the download, it is OK to open the path directly. ASP. NET file upload and download, Part 3: here we mainly talk about how to upload and download files in binary form. First, the upload method is as follows: public byte [] UpLoadFile (HtmlInputFile f_IFile) {// obtain the access to the uploaded file specified by the client HttpPostedFile upFile = f_IFile.PostedFile; // obtain the length of the uploaded file. int upFileLength = upFile. contentLength; // obtain 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. You can save it to the database. Next let's talk about this form of download. You may think that this method of download is to create An aspx page and then retrieve the binary byte stream in its Page_Load () event, then you can read it again. In fact, this method is not advisable. In actual use, there may be errors that cannot open a site. I generally use the following method: first, in the Web. add <add verb = "*" path = "openfile. aspx "type =" RuixinOA. web. baseClass. openFile, RuixinOA. web "/> indicates that I open openfile. when the aspx page is displayed, the system automatically redirects to the execution of RuixinOA. web. baseClass. the methods in the OpenFile class are implemented as follows: using System; using System. data; using System. web; using System. IO; using Ruixin. workF LowDB; using RXSuite. Base; using RXSuite. Component; using RuixinOA. BusinessFacade; namespace RuixinOA. Web. BaseClass {/** ////// NetUFile abstract description. /// Public class OpenFile: IHttpHandler {public void ProcessRequest (HttpContext context) {// retrieves the file information RuixinOA to be downloaded from the database. 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 ["CConten T "]); context. response. flush (); context. response. end () ;}} public bool IsReusable {get {return true ;}}} after executing the preceding method, the system will prompt you to choose whether to open or download the method directly. Let's talk about this part. ASP. NET file upload and download, Part 4: This part mainly describes how to upload an Internet resource to the server. First, you must reference System. net namespace, and then perform the following operations: 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 be retrieved from Int This problem can be effectively solved by reading files on ernet.
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.