文件上傳是最常用的B/S項目功能,在FileUpload控件出來之前只能使用html控件的File控件,這樣在form中就需要加入【 enctype="multipart/form-data"】。FileUpload出來后就不需要了,form就不需要做上面的更改了。
實例如下,
up1.aspx代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="up1.aspx.cs" Inherits="up1" %> <!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> <script type="text/javascript"> function checkform() { var strs = document.getElementById("FileUpload1").value; if (strs == "") { alert("請選擇要上傳的圖片!"); return false; } var n1 = strs.lastIndexOf('.') + 1; var fileExt = strs.substring(n1, n1 + 3).toLowerCase() if (fileExt != "jpg" && fileExt != "bmp" && fileExt != "png") { alert('目前系統僅支持jpg、bmp、png后綴圖片上傳!'); return false; } } </script> </head> <body> <form id="form1" runat="server"> <asp:FileUpload ID="FileUpload1" runat="server" Width="220px" /> <asp:Button ID="Button1" runat="server" CssClass="button" OnClick="Button1_Click" Text="上傳" /> </form> </body> </html>
up1.aspx.cs代碼
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; public partial class up1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button1.Attributes["onclick"] = "return checkform();"; } protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string upPath = "/up/"; //上傳文件路徑 int upLength = 5; //上傳文件大小 string upFileType = "|image/bmp|image/x-png|image/pjpeg|image/gif|image/png|image/jpeg|"; string fileContentType = FileUpload1.PostedFile.ContentType; //文件類型 if (upFileType.IndexOf(fileContentType.ToLower()) > 0) { string name = FileUpload1.PostedFile.FileName; // 客戶端文件路徑 FileInfo file = new FileInfo(name); string fileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + file.Extension; // 文件名稱,當前時間(yyyyMMddhhmmssfff) string webFilePath = Server.MapPath(upPath) + fileName; // 服務器端文件路徑 string FilePath = upPath + fileName; //頁面中使用的路徑 if (!File.Exists(webFilePath)) { if ((FileUpload1.FileBytes.Length / (1024 * 1024)) > upLength) { ClientScript.RegisterStartupScript(this.GetType(), "upfileOK", "alert('大小超出 " + upLength + " M的限制,請處理后再上傳!');", true); return; } try { FileUpload1.SaveAs(webFilePath); // 使用 SaveAs 方法保存文件 ClientScript.RegisterStartupScript(this.GetType(), "upfileOK", "alert('提示:文件上傳成功');", true); } catch (Exception ex) { ClientScript.RegisterStartupScript(this.GetType(), "upfileOK", "alert('提示:文件上傳失敗" + ex.Message + "');", true); } } else { ClientScript.RegisterStartupScript(this.GetType(), "upfileOK", "alert('提示:文件已經存在,請重命名后上傳');", true); } } else { ClientScript.RegisterStartupScript(this.GetType(), "upfileOK", "alert('提示:文件類型不符" + fileContentType + "');", true); } } } }