Asp.net File Upload solution (Image Upload, single file upload, multi-File Upload, check file type ),
I have also introduced a lot of solutions for ASP. NET File Uploading. Today I am going to upload a large collection of asp.net files.
1. upload images using standard HTML
Front-end code:
<Body> <form id = "form1" runat = "server"> <div> <table> <tr> <td colspan = "2" style = "height: 21px "> upload images using standard HTML </td> </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 image" OnClick = "UploadButton_Click"/> </td> </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) {} protected void UploadButton_Click (object sender, EventA Rgs e) {string uploadName = InputFile. value; // obtain the complete path of the image to be uploaded, including the file name // string uploadName = InputFile. postedFile. fileName; string pictureName = ""; // name of the uploaded image. The current time is used as the file name to ensure that the file name is not repeated if (InputFile. value! = "") {Int idx = uploadName. lastIndexOf (". "); string suffix = uploadName. substring (idx); // obtain the suffix of the uploaded image, 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. Upload a single file
This is the most basic file upload. This FileUpload control is not available in asp. net1.x, but only the html upload control. At that time, it is not easy to use to convert the html control into a server control. In fact, the beautiful effects of all file uploads are derived from the FileUpload control. The first example is simple but fundamental.
Front-end 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 "> simple single file upload </span> </strong> </td> </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 image" OnClick = "FileUpload_Button_Click"/> </td> </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) {} protected void FileUpload_Button_Click (object sender, E VentArgs e) {try {if (FileUpload1.PostedFile. FileName = "") // if (FileUpload1.FileName = "") // if (! FileUpload1.HasFile) // gets a value that indicates whether the System. Web. UI. WebControls. FileUpload control contains files. If the file is included, the value is true; otherwise, the value is false. {This. Upload_info.Text = "Select Upload File! ";} Else {string filepath = FileUpload1.PostedFile. fileName; // obtain the complete file path, including the file name, for example, C: \ Documents ents and Settings \ Administrator \ My Documents ents \ My Pictures \ 20022775_m.jpg // string filepath = FileUpload1.FileName; // get the uploaded file name 20022775_m.jpg string filename = filepath. substring (filepath. lastIndexOf ("\") + 1); // 20022775_m.jpg string serverpath = Server. mapPath ("~ /Images/") + filename; // obtain the file stored on the server at C: \ Inetpub \ wwwroot \ WebSite1 \ images \ 20022775_m.jpg FileUpload1.PostedFile. saveAs (serverpath); // Save the uploaded file as this. upload_info.Text = "Upload successful! ";}} Catch (Exception ex) {this. Upload_info.Text =" Upload error! Cause: "+ ex. ToString ();}}}
3. Multifile upload
Front-end code:
<Body> <form id = "form1" runat = "server"> <div> <table style = "width: 343px"> <tr> <td style = "width: 100px "> Multifile upload </td> <td style =" width: 100px "> </td> </tr> <td style =" width: 100px "> <asp: FileUpload ID =" FileUpload1 "runat =" server "Width =" 475px "/> </td> <td style =" width: 100px "> </td> </tr> <td style =" width: 100px "> <asp: fileUpload ID = "FileUpload2" runat = "server" Width = "475px"/> </td> <td style = "width: 100px "> </td> </tr> <td style =" width: 100px "> <asp: fileUpload ID = "FileUpload3" runat = "server" Width = "475px"/> </td> <td style = "width: 100px "> </td> </tr> <td style =" width: 100px "> <asp: button ID = "bt_upload" runat = "server" OnClick = "bt_upload_Click" Text = "Upload together"/> <asp: label ID = "lb_info" runat = "server" ForeColor = "Red" Width = "448px"> </asp: Label> </td> <td style = "width: 100px "> </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) {} protected void bt_upload_Click (object sender, EventArgs E) {if (FileUpload1.PostedFile. fileName = "" & FileUpload2.PostedFile. fileName = "" & FileUpload3.PostedFile. fileName = "") {this. lb_info.Text = "select a file! ";} Else {HttpFileCollection myfiles = Request. files; for (int I = 0; I <myfiles. count; I ++) {HttpPostedFile mypost = myfiles [I]; try {if (mypost. contentLength> 0) {string filepath = mypost. fileName; // C: \ Documents ents and Settings \ Administrator \ My Documents ents \ My Pictures \ 20022775_m.jpg string filename = filepath. substring (filepath. lastIndexOf ("\") + 1); // 20022775_m.jpg string serverpath = Server. MapPath ("~ /Images/") + filename; // C: \ Inetpub \ wwwroot \ WebSite2 \ images \ 20022775_m.jpg mypost. SaveAs (serverpath); this. lb_info.Text =" uploaded successfully! ";}} Catch (Exception ex) {this. lb_info.Text =" Upload error! Cause: "+ ex. Message. ToString ();}}}}}
4. Check the upload file type on the client (the upload image is used as an example)
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %> <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <Html xmlns =" http://www.w3.org/1999/xhtml "> <Head runat =" server "> <title> check the upload file type on the client </title> <script language =" javascript "> function Check_FileType () {var str = document. getElementById ("FileUpload1 "). value; var pos = str. lastIndexOf (". "); var lastname = str. substring (pos, str. length); if (lastname. toLowerCase ()! = ". Jpg" & lastname. toLowerCase ()! = ". Gif ") {alert (" the file type you uploaded is "+ lastname +", and the image category is .jpg, .gif "); return false ;}else {return true ;}} </script>
Note: When you Click Upload, the client event OnClientClick = "return Check_FileType ()" is triggered first ()"
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) {} protected void bt_upload_Click (object sender, EventArgs E) {try {if (FileUpload1.PostedFile. FileName = "") {this. lb_info.Text = "select a file! ";} Else {string filepath = FileUpload1.PostedFile. FileName; // if (! IsAllowedExtension (FileUpload1) // {// this. lb_info.Text = "the format of the uploaded file is incorrect! "; //} 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 =" uploaded successfully! ";} Else {this. lb_info.Text =" upload an image! ";}} Catch (Exception ex) {this. lb_info.Text =" Upload error! Cause: "+ 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; // obtain the complete file path strExtension = strOldFilePath. substring (strOldFilePath. lastIndexOf (". "); // get the file extension, such :. jpg for (int I = 0; I <arrExtension. length; I ++) {if (strExtension. equals (arrExtension [I]) {return true ;}}return false ;}}
Note: If the client script and client event OnClientClick = "return Check_FileType ()" are removed
Changed:
If (! IsAllowedExtension (FileUpload1) {this. lb_info.Text = "the format of the uploaded file is incorrect! ";}
Else if (IsAllowedExtension (FileUpload1) = true)
That is, the type of the uploaded file is checked by the server.
5. Check the type of the uploaded file on the server (the real file format)
<Body> <form id = "form1" runat = "server"> <div> <table> <tr> <td colspan = "2"> server checks the upload file type </ td> </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 image" OnClick = "bt_upload_Click"/> </td> </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) {} protected void bt_upload_Click (object Sender, EventArgs e) {try {if (FileUpload1.PostedFile. FileName = "") {this. lb_info.Text = "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 successful! ";}Else {this. lb_info.Text =" Upload image ";}}} catch (Exception error) {this. lb_info.Text =" Upload error! Cause: "+ 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 ;}}}
Whether the content is wonderful. If you like it, add it to your favorites. It will be helpful in the future when you encounter ASP. NET File Upload problems.