C# ASP.NET上傳控制元件fileupload的使用
阿新 • • 發佈:2019-01-03
程式碼實現了簡單的圖片上傳功能(改一下也可以上傳其他的),沒有做圖片大小和格式的判斷,主要是熟悉fileupload控制元件
介面程式碼:
後臺程式碼:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication2.WebForm3" %> <!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></title> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="FileUpload1" runat="server" /><br /> <asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" /> <asp:Label ID="Label1" runat="server" Text=""></asp:Label> <br /> <asp:Image ID="Image1" runat="server" visible="false" /> <br /> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication2 { public partial class WebForm3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) //判斷是否上傳了檔案 { string savePath = Server.MapPath("~/upload/");//指定上傳檔案在伺服器上的儲存路徑 //檢查伺服器上是否存在這個物理路徑,如果不存在,則建立 if (!System.IO.Directory.Exists(savePath)) { //對該路徑應該有足夠的許可權,否則報錯 System.IO.Directory.CreateDirectory(savePath); } savePath = savePath + "\\" + FileUpload1.FileName; FileUpload1.SaveAs(savePath); //儲存檔案 Label1.Text = string.Format("<a href='upload/{0}'>upload/{0}</a>", FileUpload1.FileName); Image1.Visible = true; Image1.ImageUrl = "~/upload/" + FileUpload1.FileName; } } } }
其中,特別要注意的是檔案路徑問題,就是我最後刺耳的image1的url地址。,要使用相對路徑