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)上传成功的标志为重命名的图片上传到服务器上,而且数据库中存储图片路径的字段修改为功post

 

 

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

private void ProcessUpload(int pid)
        {
            //1.0获得上传过来文件
            HttpFileCollection fils = Request.Files;//获得上传过来的文件

            if (fils.Count > 0)
            {
                if (fils[0].ContentLength > 0)
                {
                    //2.0上传图片之后要将图片的名称作一个修改(不能重复)
                    string oldName = fils[0].FileName;
                    //获得当前名称的后缀
                    string extName = System.IO.Path.GetExtension(oldName);
                    //生成一个永不重复的名称
                    string newName = Guid.NewGuid() + extName;


                    using (Image img = Image.FromStream(fils[0].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();
                }
            }
        }
相关文章
相关标签/搜索