asp.net file upload solution (picture upload, single file upload, multiple file upload, check file type) _ Practical skills

Source: Internet
Author: User

Small set up before also introduced a lot of asp.net file upload solution case, today to a asp.net file upload large collection.

1 using standard HTML for image upload
Foreground code:

<body> 
 <form id= "Form1" runat= "Server" > 
 <div> 
  <table> 
   <tr> 
    <TD colspan= "2" style= "height:21px" > 
     using standard HTML for image upload </td> 
   </tr> 
   <tr> 
    <TD style= "width:400px" > 
     <input id= "Inputfile" style= "width:399px" type= "file" runat= "Server"/> </td> 
    <td style= "width:80px" > 
     <asp:button id= "Uploadbutton" runat= "server" text= "Upload picture" onclick= "Uploadbutton_click"/></td> 
   </tr> 
   <tr> 
    <td colspan= "2" > 
     <asp:label id= "Lb_info" runat= "Server" forecolor= "Red" ></asp:Label></td>     
   </tr> 
  </table>  
 </div> 
 </form> 
</body>


Background code:

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; Public partial class _default:system.web.ui.page {protected void Page_Load (object sender, EventArgs e) {} PR otected void Uploadbutton_click (object sender, EventArgs e) {string uploadname = inputfile.value;//Gets the full path to the uploaded picture, including the file 
  Name//string uploadname = InputFile.PostedFile.FileName; String picturename = "";//the name of the picture after the upload, with the current time as the filename, ensure that the filename does not have a duplicate if (Inputfile.value!= "") {int idx = Uploadname.lastinde 
   XOf ("."); 
  string suffix = uploadname.substring (idx);//Get the suffix name of the uploaded picture Picturename = DateTime.Now.Ticks.ToString () + suffix; 
    try {if (uploadname!= "") {string path = Server.MapPath ("~/images/"); 
   InputFile.PostedFile.SaveAs (path + picturename); } catch (Exception ex) {ResPonse. 
  Write (ex); } 
 } 
}

2 Single File upload
This is the most basic file upload, in asp.net1.x without this fileupload control, only HTML upload control, then to the HTML control into server control, very difficult to use. In fact, all the beautiful effect of the file upload is derived from this FileUpload control, the first example, although simple is fundamental.
Foreground code:

<body> 
 <form id= "Form1" runat= "Server" > 
 <div> 
  <table style= "width:90%" > 
   <tr> 
    <td style= "width:159px" colspan=2> 
     <strong><span style= "font-size:10pt" > Simplest single file upload </span></strong></td> 
   </tr> 
   <tr> 
    <td style= "width:600px" > 
     <asp:fileupload id= "FileUpload1" runat= "Server" width= "600px"/></td> <td align=left 
    > 
     <asp:button id= "Fileupload_button" runat= "server" text= "Upload picture" onclick= "Fileupload_button_click"/> </td> 
   </tr> 
   <tr> 
    <td colspan=2> 
     <asp:label id= "Upload_info" runat= "Server" forecolor= "Red" width= "767px" ></asp:Label></td> 
   </tr> 
  </table>  
 </div> 
 </form> 
</body>

Background code:

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; Public partial class _default:system.web.ui.page {protected void Page_Load (object sender, EventArgs e) {} PR otected void Fileupload_button_click (object sender, EventArgs e) {try {if (FileUpload1.PostedFile.FileName = = "")//if (Fileupload1.filename = = "")//if (! Fileupload1.hasfile)//Gets a value indicating whether the System.Web.UI.WebControls.FileUpload control contains files. 
   Is true if the file is included, or false. {this. Upload_info. Text = "Please select Upload file!" 
   "; else {string filepath = FileUpload1.PostedFile.FileName;//Gets the full path to the file, including the file name, such as: C:\Documents and Settings\a    Dministrator\my Documents\My Pictures\20022775_m.jpg//string filepath = fileupload1.filename; Get uploaded filename 20022775_m.jpg string filename = filepath. Substring (FilepaTh. LastIndexOf ("\") + 1);//20022775_m.jpg string serverpath = Server.MapPath ("~/images/") + filename;//gets the location where the file is saved on the server C: \inetpub\wwwroot\website1\images\20022775_m.jpg FileUpload1.PostedFile.SaveAs (Serverpath);//save uploaded file as this. Upload_info. Text = "Upload success!" 
   "; } catch (Exception ex) {this. Upload_info. Text = "Upload Error!" The reason is: "+ ex." 
  ToString (); } 
 } 
}


3, multiple file upload
foreground code:

&lt;body&gt; &lt;form id= "Form1" runat= "Server" &gt; &lt;div&gt; &lt;table style= "width:343px" &gt; &lt;tr&gt; &LT;TD style= "width:100px" &gt; Multi-File Upload &lt;/td&gt; &lt;td style= "width:100px" &gt; &lt;/td&gt; &lt;/ tr&gt; &lt;tr&gt; &lt;td style= "width:100px" &gt; &lt;asp:fileupload id= "FileUpload1" runat= "Server" width= 
    "475px"/&gt; &lt;/td&gt; &lt;td style= "width:100px" &gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; 
    &LT;TD style= "width:100px" &gt; &lt;asp:fileupload id= "FileUpload2" runat= "Server" width= "475px"/&gt;&lt;/td&gt; 
     &LT;TD style= "width:100px" &gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style= "width:100px" &gt; &lt;asp:fileupload id= "FileUpload3" runat= "Server" width= "475px"/&gt;&lt;/td&gt; &lt;td "style=" 
    ; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style= "width:100px" &gt; &lt;asp:button id= "bt_upload" runat= "Server" onclick="Bt_upload_click" text= "Upload"/&gt; &lt;asp:label id= "lb_info" runat= "Server" forecolor= "Red" width= "448px" &gt;&lt;/ asp:label&gt;&lt;/td&gt; &lt;td style= "width:100px" &gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/di V&gt; &lt;/form&gt; &lt;/body&gt;


Background code:

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; Public partial class _default:system.web.ui.page {protected void Page_Load (object sender, EventArgs e) {} PR otected void Bt_upload_click (object sender, EventArgs e) {if (FileUpload1.PostedFile.FileName = "" &amp;&amp; Fileu Pload2. Postedfile.filename = = "" &amp;&amp; FileUpload3.PostedFile.FileName = "") {This.lb_info. Text = "Please select a file!" 
  "; 
   else {httpfilecollection myfiles = request.files; for (int i = 0; i &lt; myfiles. Count; 
    i++) {Httppostedfile mypost = myfiles[i]; try {if (mypost). ContentLength &gt; 0) {string filepath = MyPost. Filename;//c:\documents and Settings\Administrator\My documents\my pictures\20022775_m.jpg string filename = Filepa Th. SubstriNg (filepath. LastIndexOf ("\") + 1);//20022775_m.jpg string serverpath = Server.MapPath ("~/images/") + filename;//c:\inetpub\www Root\website2\images\20022775_m.jpg MyPost. 
      SaveAs (Serverpath); This.lb_info. Text = "Upload success!" 
     "; } catch (Exception ex) {this.lb_info. Text = "Upload Error!" Reason: "+ ex." 
    Message.tostring (); } 
   } 
  } 
 } 
}

4, the client checks the upload file type (for example, the picture above)

&lt;%@ Page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits= "_default"%&gt; &lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;html xmlns=" http://www.w3.org/1999/xhtml "&gt; &lt;head runat=" Server "&gt; &lt;title&gt; client Check upload file type &lt;/ti Tle&gt; &lt;script language= "JavaScript" &gt; Function Check_filetype () {var Str=document.getelementbyid ("Fileupl 
  Oad1 "). Value; 
  var pos=str.lastindexof ("."); 
  var lastname=str.substring (pos,str.length); if (Lastname.tolowercase ()!= ". jpg" &amp;&amp;lastname.tolowercase ()!= ". gif") {alert ("The file type you are uploading is" +lastname+ ", 
   The picture must be a. Jpg,.gif type "); 
  return false; 
  else {return true; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id= "Form1" runat= "Server" &gt; &lt;div&gt; &lt;table &gt; &lt;tr&gt; &lt;td colspan= "2" &gt; Client check Upload file type &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;tD style= "width:444px" &gt; &lt;asp:fileupload id= "FileUpload1" runat= "Server" width= "432px"/&gt;&lt;/td&gt; &L T;TD style= "width:80px" &gt; &lt;asp:button id= "bt_upload" runat= "server" text= "Upload picture" onclick= "Bt_upload_click" OnCl  ientclick= "return Check_filetype ()"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan= "2" style= "Height:     
   21px "&gt; &lt;asp:label id=" lb_info "runat=" Server "forecolor=" Red "width=" 515px "&gt;&lt;/asp:Label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;

Note: Click Upload to trigger the client event first onclientclick= "Return Check_filetype ()"

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; Public partial class _default:system.web.ui.page {protected void Page_Load (object sender, EventArgs e) {} p 
   rotected void Bt_upload_click (object sender, EventArgs e) {try {if (FileUpload1.PostedFile.FileName = "") {This.lb_info. Text = "Please select a file!" 
   "; 
    else {string filepath = FileUpload1.PostedFile.FileName; if (! Isallowedextension (FILEUPLOAD1))//{//This.lb_info. Text = "Upload file format is not correct!" 
    "; } if (Isallowedextension (FileUpload1) = = true) {string filename = filepath. Substring (filepath. 
     LastIndexOf ("\") + 1); 
     String serverpath = Server.MapPath ("~/images/") + filename; 
     FileUpload1.PostedFile.SaveAs (Serverpath); This.lb_info. Text = "Upload success!" 
   "; else {this.lb_info. Text = "Please upload pictures!" 
    "; The catch (Exception ex) {this.lb_info. Text = "Upload Error!" Reason: "+ ex." 
  ToString (); 
  } private static bool Isallowedextension (FileUpload upfile) {string stroldfilepath = ""; 
  String strextension= ""; 
  String[] arrextension ={". gif", ". jpg", ". bmp", ". png"}; if (upfile. Postedfile.filename!= String. Empty) {Stroldfilepath = Upfile. postedfile.filename;//gets the full pathname of the file strextension = stroldfilepath.substring (Stroldfilepath.lastindexof ("."));  
    /Obtain the file extension, such as:. jpg for (int i = 0; i &lt; arrextension.length; i++) {if (Strextension.equals (arrextension[i))) 
    {return true; 
 }} return false; } 
}

Note: If you remove the client script and client event onclientclick= "return Check_filetype ()", in the background code
To

if (! Isallowedextension (FILEUPLOAD1)) 
    { 
     this.lb_info. Text = "Upload file format is not correct!" "; 
    


else if (isallowedextension (FileUpload1) = = True)
That becomes the server-side check upload file type.
5, server-side check upload file type (file inside the real format)

<body> 
 <form id= "Form1" runat= "Server" > 
 <div> 
  <table> 
   <tr> 
    <TD colspan= "2" > 
     server Check upload file type </td>     
   </tr> 
   <tr> 
    <td style= "width:444px" > 
     <asp:fileupload id= FileUpload1 runat= "Server" width= "432px"/></td> <td style= 
    " width:80px "> 
     <asp:button id=" bt_upload "runat=" server "text=" Upload picture "onclick=" Bt_upload_click "/></ td> 
   </tr> 
   <tr> 
    <td colspan= "2" style= "height:21px" > 
     <asp:label id= "lb _info "runat=" Server "forecolor=" Red "width=" 515px "></asp:Label></td>     
   </tr> 
  </ table>  
 </div> 
 </form> 
</body>

Background code:

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; Public partial class _default:system.web.ui.page {protected void Page_Load (object sender, EventArgs e) {} PR 
   otected void Bt_upload_click (object sender, EventArgs e) {try {if (FileUpload1.PostedFile.FileName = "") {This.lb_info. Text = "Please select a file!" 
   "; 
    else {string filepath = FileUpload1.PostedFile.FileName; if (isallowedextension (FileUpload1) = = true) {string filename = filepath. Substring (filepath. 
     LastIndexOf ("\") + 1); 
     String serverpath = Server.MapPath ("images/") + filename; 
     FileUpload1.PostedFile.SaveAs (Serverpath); This.lb_info. Text = "Upload success!" 
    "; else {this.lb_info. 
    Text = "please upload pictures"; catch (ExceptiOn error) {This.lb_info. Text = "Upload Error!" Reason: "+ error." 
  ToString (); }} private static bool Isallowedextension (FileUpload upfile) {FileStream fs = new FileStream (upfile. 
  Postedfile.filename, FileMode.Open, FileAccess.Read); 
  BinaryReader r = new BinaryReader (FS); 
  String fileclass = ""; 
  byte buffer; 
   try {buffer = R.readbyte (); Fileclass = buffer. 
   ToString (); 
   Buffer = R.readbyte (); Fileclass + = buffer. 
  ToString (); 
  Catch {} r.close (); Fs. 
  Close (); if (Fileclass = = "255216" | | fileclass = = "7173" | | fileclass== "6677" | | 
  fileclass== "13780")//Description 255216 is jpg;7173 is gif;6677 is bmp,13780 is png;7790 is exe,8297 is rar {return true; 
  else {return false; } 
 } 
}

For everyone to recommend a special topic for everyone to learn:"ASP." NET file Upload Summary "

Is the content is very wonderful, like friends to collect it, later in the encounter asp.net file upload problem can help.
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.