实现文件上传" type="hidden"/>

asp.net/c# 用实现文件上传


<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"标记可选


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM