<input type="file" />我們常用的上傳文件的工具(控件),它和 <asp:FileUpload ID="FileUpload1" runat="server" />不一樣,在后台不能直接獲取到,不能像
this.FileUpload1.PostedFile……那樣去獲取
而有時我們必須使用<input type="file" />,如動態給頁面添加好多個<input type="file" />,你們后台要怎么獲取呢
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <form runat="server" id="form1" method="post" > <input name="f" type="file" /> <input name="s" type="submit" /> </form> </body> </html>
后台代碼:
public void UploadImg()
{
System.Web.HttpFileCollection _file = System.Web.HttpContext.Current.Request.Files;
if (_file.Count > 0)
{
long size = _file[0].ContentLength; //文件大小
string type = _file[0].ContentType; //文件類型
string name = _file[0].FileName; //文件名
string _tp = Path.GetExtension(name);//文件擴展名
if (_tp.ToLower() == ".jpg" || _tp.ToLower() == ".jpeg" || _tp.ToLower() == ".gif" || _tp.ToLower() == ".png" || _tp.ToLower() == ".swf")
{
Stream stream = _file[0].InputStream;//獲取文件流
string savaName = DateTime.Now.ToString("yyyyMMddHHssmm") + _tp; //保存文件
string filepath = "/UploadFile/" + savaName;
string path = Server.MapPath(filepath);
_file[0].SaveAs(path);
}
}
}
寫成這樣,我們發現每次獲得的_file.Count 都是0
我們需要為form加上enctype="multipart/form-data"的屬性
表單中enctype="multipart/form-data"的意思,是設置表單的MIME編碼。默認情況,這個編碼格式是application/x-www-form-urlencoded,不能用於文件上傳;只有使用了
multipart/form-data,才能完整的傳遞文件數據,進行下面的操作
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <form runat="server" id="form1" method="post" enctype="multipart/form-data"> <input name="f" type="file" /> <input name="s" type="submit" /> </form> </body> </html>
后台獲取到了Request.Files
我們為form 加上runat="server" action可以指向其他頁面
總結:
1.form 必須有runat="server"標記,
2.form 必須有enctype="multipart/form-data"標記,
3.<input type="file" />的runat="server"標記可選