HTML的代码:(关键是要在form里设置enctype="multipart/form-data",这样才能在提交表单时,将文件以二进制流的形式传输到服务器)
一、
<form id="form1" action="test.aspx" method="post" enctype="multipart/form-data"> <div> <input type="file" name="fl" /> <input type="submit" name="sb" value="submit" /> </div> </form>
public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFile PostedFile = Request.Files[i]; if (PostedFile.ContentLength > 0) { string FileName = PostedFile.FileName; string strExPrentFile = FileName.Substring(FileName.LastIndexOf(".") + 1); string sFilePath = Server.MapPath("~/") + FileName;// Server.MapPath("~/123." + strExPrentFile); PostedFile.SaveAs(sFilePath); } else { //this.LabMessage.Text = "不能上传空文件"; } } Response.Write("1"); } } }
二、
<form id="form1" runat="server" method="post" enctype="multipart/form-data"> <div> <input type="file" /> <asp:Button ID="btnUpload" runat="server" Text="开始上传" onclick="btnUpload_Click" /> </div> </form>
protected void btnUpload_Click(object sender, EventArgs e) { //int intCount = RequestClass.GetFormInt("hdcount", -1); HttpFileCollection Files = HttpContext.Current.Request.Files; for (int i = 0; i < Files.Count; i++) { HttpPostedFile PostedFile = Files[i]; if (PostedFile.ContentLength > 0) { string FileName = PostedFile.FileName; string strExPrentFile = FileName.Substring(FileName.LastIndexOf(".") + 1); string sFilePath = "/uploadfile/hotel/" + StringClass.makeFileName24() + i + strExPrentFile; PostedFile.SaveAs(Server.MapPath(sFilePath)); } else { //this.LabMessage.Text = "不能上传空文件"; } } }
时间: 2024-08-27 14:07:01