您的位置:首页 > 编程语言 > ASP

asp.net/c# 用<input type="file" />实现文件上传,multipart/form-data

2013-08-03 17:19 1076 查看
<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>


后台代码:

 

//客户端上传的文件
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 = System.IO.Path.GetExtension(name);

if (_tp.ToLower() == ".jpg" || _tp.ToLower() == ".jpeg" || _tp.ToLower() == ".gif" || _tp.ToLower() == ".png" || _tp.ToLower() == ".swf")
{
//获取文件流
System.IO.Stream stream = _file[0].InputStream;
//保存文件
string saveName = DateTime.Now.ToString("yyyyMMddHHmmss") + _tp;
string path = DataFactory.WFile.FileUploadPath + "/upload/area/" + saveName;
_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"标记可选

 

                                                                                                                                                                  烟台社区:http://ythome.cn

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐