This article for everyone to share the FileUpload control to upload pictures and preview the image of the function, and the Web.config configuration, first look at the final results:
Page code:
<form id= "Form1" runat= "Server" >
<div>
<asp:fileupload id= "FileUpload1" runat= "Server"/>
<asp:button id= "Button1" runat= "server" text= "upload" width= "54px" onclick= "Button1_Click"/> <asp
: Label id= "Label1" runat= "Server" text= "style= color:red" ></asp:Label> <asp:image runat= "
Server" ID = "Image1" style= "z-index:102"; left:20px; Position:absolute;
Top:49px "width=" 73px "/>
</div>
</form>
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; namespace Web.file {public partial class WebForm1:System.Web.UI.Page {protected void Page_Load (object sender, Event Args e) {} #region File upload///<summary>///file upload///</summary> protected void Button1_Click (object sen Der, EventArgs e) {if (Fileupload1.filename = = "") {this.
Label1.Text = "Upload file cannot be empty";
Return
BOOL Fileisvalid = false; If the upload file is confirmed, determine if the file type meets the requirements if (this. Fileupload1.hasfile) {//Get upload file suffix String fileextension = System.IO.Path.GetExtension (this. Fileupload1.filename).
ToLower ();
String[] restrictextension = {". gif", ". jpg", ". bmp", ". png"};
Determine if the file type meets the requirements for (int i = 0; i < restrictextension.length i++) {if (fileextension = = Restrictextension[i]) {Fileisvalid = True ///If the file type meets the requirements, invoke the SaveAs method to implement the upload and display the relevant information if (Fileisvalid = = true) {//upload file is greater than 10M if (fileupload1.postedfile). ContentLength > (* 1024 * 1024)) {this.
Label1.Text = "Upload file too large";
Return try {this.
Image1.imageurl = "~/file/" + fileupload1.filename; This.
Fileupload1.saveas (Server.MapPath ("~/file/") + Fileupload1.filename); This.
Label1.Text = "File upload success!"; The catch {this. Label1.Text = "File upload failed!"
"; The finally {}} else {this.
Label1.Text = "can only upload the suffix to. gif,.jpg,.bmp,.png file";
}}} #endregion}}
Web.config configuration:
<!--because the FileUpload control upload maximum 4M, if you want to upload a larger file, change the size of the maxRequestLength-->
<configuration>
< system.web>
<compilation debug= "true" targetframework= "4.0"/>
3 wonderful topics to be attached:
Asp. NET Control Usage Manual
Asp. NET data-bound controls using totals
Asp. NET controls use totals
Pro, you can implement FileUpload control in your own project upload pictures and preview the image of the function, so that the site is more practical, the basic steps are these, there may be a small part of the missing places, I hope you understand.