Webform (File upload)

Source: Internet
Author: User
Tags server memory

1.HTML Encoding:

<input type= "File"/>

2. Control: FileUpload

It is used to select files to upload, and a button is required to upload the selected files to the server

String path = "images/" + fileupload1.filename;
Fileupload1.saveas (Server.MapPath (path));

Optimization 1: The file retains its original name and suffix

String path = "images/" + fileupload1.filename;

Optimization 2: Prevent duplicate names, or multiple people at the same time upload the same name file

String path = "images/" + DateTime.Now.ToString ("Yyyymmddhhssmmms") + request.cookies["Ures"]. Value + fileupload1.filename;

Optimization 3: Can upload large files, default is 4MB,4096KB
Method: Expansion

Add the following sentence to the system.web tag in Web. config:

Note: Do not expand too much, because if multiple people upload large files at the same time, it may cause server memory overflow, causing the server to crash.

Optimization 4: Exceeding the size of the upload request, preventing uploading and prompting the file to be too large
C # Side resolution:

if (fileupload1.postedfile.contentlength> (1024*1024*10)) {labei1.text= "file more than 10M, do not upload such a large! "; return;}

C # End is bad, because if the file exceeds the maximum length, the C # end is limited, and the program crashes directly

JS End:

document.getElementById ("Button1"). onclick = function () {        //Remove the upload element        var fi1 = document.getElementById (" FileUpload1 ");        Determine if there is a selected file        if (fi1.value.length <= 0) {            alert (' Please select a file to upload! ');            return false;        }        else {            //Verify that the selected file length meets the condition            if (fi1.files[0].size > (1024x768 *))            {                alert (' file is too large to allow uploading! ');                return false;}}    ;

Optimization 5: Limit the types of files that can be selected

In the FileUpload property, add accept= ". Jpg,.jpeg,.png"

Breakpoint Continuation:

 1 using System;  2 using System.Data;  3 using System.Configuration;  4 using System.Collections;  5 using System.Web;  6 using System.Web.Security;  7 using System.Web.UI;  8 using System.Web.UI.WebControls; 9 using System.Web.UI.WebControls.WebParts; Ten using System.Web.UI.HtmlControls; One using System.IO; Public partial class DFile:System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) 15 {16} protected void Linbtndfile_click (object sender, EventArgs e) 18 {19//Create one-bit array [byte[] buffer = new byte[10240]; 21 Specifies the path to the file to download. String filePath = @ "D:\-ji-ai-nook. rar"; 23//or take file name including extension of string filename = Path.getfilename (FilePath); Stream fileStream = null; $ try 27 {28//Open File FileStream = new FileStream (FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); Se. Clear (); 31//Get file Size: FileSize = filestream.length; A long sum = 0; if (request.headers["Range"] = null) {Response.statuscode = 206;//HTTP returned to the clientAn integer that outputs the state. The default value is 200. PNS sum = long. Parse (request.headers["Range"). Replace ("bytes=", ""). Replace ("-", "")); (sum! = 0) Response.AddHeader ("Content-range", "bytes" + sum.) ToString () + "-" + ((long) (fileSize)). ToString () + "/" + filesize.tostring ()); 42} 43//Get partial HTTP header information for Response.AddHeader ("Content-length", ((Long) (Filesize-sum)). ToString ()); Response.ContentType = "Application/octet-stream"; 46//Get File Source Response.AddHeader ("content-disposition", "attachment; Filename= "+ Httputility.urlencode (Request.ContentEncoding.GetBytes (fileName)); //Response.Flush (); filestream.position = sum; Sets the current flow position of fileSize = filesize-sum; 51//When the size of the file is greater than 0 is into the loop of the (FileSize > 0) 53 {54//Determine if the client is still connected to the server if (response.isclientconnected) 56 {57//Get Slow The total number of bytes in the flush area. filestream.read int length = n/A (buffer, 0, 10240); 59//Write Data Response.OutputStream.Write (buffer, 0, length); 61//The output of the buffer is sent to client Response.Flush (); Buffer = new byte[10240]; FileSize = FilesizE-length;  $67} (68) (if the user disconnects and exits the loop, fileSize =-1;) (Exception ex) ("Error: "+ Ex. Message);  $80 {81//Close file Filestream.close (); response.end} (); 85} 86} 87---  }

Webform (file upload)

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.