aspx页面中用Input 标签实现上传图片功能

实现上传图片功能需单独的建立一个aspx页面,
其中前台页面需要注意两点:
a)实现上传功能的input的type="file"
b)设置请求报文头为 enctype="multipart/form-data" 类型

前台代码如下:

<form method="post" enctype="multipart/form-data">
<table class="list">
<tr>
<th>上传</th>
<td>
<input type="file" name="f1" /></td>
</tr>
<tr>
<th></th>
<td>
<input type="submit" value="上传" /></td>
</tr>
</table>
</form>

在后台.cs文件中需注意几点:
a)使用 Request.Files 从请求报文中获得上传过来的文件

b)上传到服务器中需要重命名一个永不重复的文件,使用 Guid.NewGuid()
string newName = Guid.NewGuid() + extName;

c)上传成功的标志为重命名的图片上传到服务器上,并且数据库中存储图片路径的字段修改成功

后台处理上传的方法 ProcessUpload() 代码如下:

private void ProcessUpload(int pid)
{
//1.0得到上传过来文件
HttpFileCollection fils = Request.Files;//得到上传过来的文件 if (fils.Count > )
{
if (fils[].ContentLength > )
{
//2.0上传图片以后要将图片的名称做一个修改(不能重复)
string oldName = fils[].FileName;
//得到当前名称的后缀
string extName = System.IO.Path.GetExtension(oldName);
//生成一个永不重复的名称
string newName = Guid.NewGuid() + extName; using (Image img = Image.FromStream(fils[].InputStream))
{
//将图片流保存到服务器路径上
img.Save(Server.MapPath("/upload/img/") + newName); //将数据库中数据对应对象的图片名称改为当前图片的名称
BlogPhotoBLL bll = new BlogPhotoBLL();
BlogPhoto model = bll.GetModel(pid);
//修改图片的名称
model.PSrc = newName;
//提交,修改数据库图片的名称
if (bll.Update(model))
{
Response.Write("<script>alert('上传成功');window.location='/0906/Photo/PhotoList.aspx?albId=" + albId + "'</script>");
Response.End();
}
}
}
else
{
Response.Write("<script>alert('您还没有选中文件');window.location=window.location</script>");
Response.End();
}
}
}
上一篇:c# SerialPort会出现“已关闭 Safe handle”的错误


下一篇:MySQL自用脚本(不定期更新)