文件上传是最常用的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); } } } }