本文為大家分享了fileupload控件實現上傳圖片后并進行預覽圖片的功能,并對web.config進行了配置,先看一下最終效果:
頁面代碼:
1
2
3
4
5
6
7
8
9
|
< form id = "form1" runat = "server" > < div > < asp:FileUpload ID = "FileUpload1" runat = "server" /> < asp:Button ID = "Button1" runat = "server" Text = "上傳" 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 > |
后臺代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
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, EventArgs e) { } #region 文件上傳 /// <summary> /// 文件上傳 /// </summary> protected void Button1_Click( object sender, EventArgs e) { if (FileUpload1.FileName == "" ) { this .Label1.Text = "上傳文件不能為空" ; return ; } bool fileIsValid = false ; //如果確認了上傳文件,則判斷文件類型是否符合要求 if ( this .FileUpload1.HasFile) { //獲取上傳文件的后綴 String fileExtension = System.IO.Path.GetExtension( this .FileUpload1.FileName).ToLower(); String[] restrictExtension = { ".gif" , ".jpg" , ".bmp" , ".png" }; //判斷文件類型是否符合要求 for ( int i = 0; i < restrictExtension.Length; i++) { if (fileExtension == restrictExtension[i]) { fileIsValid = true ; } //如果文件類型符合要求,調用SaveAs方法實現上傳,并顯示相關信息 if (fileIsValid == true ) { //上傳文件是否大于10M if (FileUpload1.PostedFile.ContentLength > (10 * 1024 * 1024)) { this .Label1.Text = "上傳文件過大" ; return ; } try { this .Image1.ImageUrl = "~/File/" + FileUpload1.FileName; this .FileUpload1.SaveAs(Server.MapPath( "~/File/" ) + FileUpload1.FileName); this .Label1.Text = "文件上傳成功!" ; } catch { this .Label1.Text = "文件上傳失敗!" ; } finally { } } else { this .Label1.Text = "只能夠上傳后綴為.gif,.jpg,.bmp,.png的文件" ; } } } } #endregion } } |
Web.config 配置:
1
2
3
4
5
6
7
|
<!--因為FileUpload 控件上傳最大為4M,如果要上傳更大文件,改下maxRequestLength的大小--> < configuration > < system.web > < compilation debug = "true" targetFramework = "4.0" /> < httpRuntime requestValidationMode = "2.0" maxRequestLength = "10485760" executionTimeout = "3600" appRequestQueueLimit = "10000" /> </ system.web > </ configuration > |
親,你可以在自己的項目中實現fileupload控件上傳圖片并進行預覽圖片的功能,這樣網站更具有實用性,基本步驟就是這些,可能還有小編遺漏的地方,希望大家諒解。