黑马程序员技术交流社区

标题: 如何上传图片 [打印本页]

作者: 王雪磊    时间: 2012-4-18 00:55
标题: 如何上传图片
如何上传图片,到指定文件夹,并保存,来个详解的,
作者: 崔楠    时间: 2012-4-18 11:02
要用FileUpload吧,我写过一段从电脑中选择图片保存的解决方案下面Photos文件夹的代码,asp.net的你参考看看,

前台:
<div id="PhotoInfo">
    <ul>
       <li>
            选择照片:<asp:FileUpload ID="fulPhoto" runat="server" />      
        </li>
        <li>
            <asp:Image runat="server" ID="imgPhoto" Height="160px" Width="230px" />
            &nbsp;<asp:Button ID="btnUpLoad" runat="server" Text="上传"
                onclick="btnUpLoad_Click" /><br />
            &nbsp;<asp:Label ID="lblMessage" runat="server" Text="图片上传成功!" ForeColor="Blue" Visible="false"></asp:Label>
        </li>   
     </ul>
</div>

后台:
        protected void btnUpLoad_Click(object sender, EventArgs e)
        {
            string name = this.fulPhoto.FileName;
                bool fileOK = false;

                if (this.fulPhoto.HasFile)
                {
                    string fileExtension = Path.GetExtension(name).ToLower();
                    string[] allowExtension = { ".gif", ".jepg", ".jpg", ".png", ".bmp" };
                    foreach (string f in allowExtension)
                    {
                        fileOK = true;
                        break;
                    }
                }

                if (fileOK)
                {
                    string strPath = Server.MapPath(@".\") + "Photos\\";

                    this.fulPhoto.PostedFile.SaveAs(strPath + name);
                    this.imgPhoto.ImageUrl = "Photos\\" + name;
                    this.lblMessage.Visible = true;
                    //this.fulPhoto.SaveAs(strPath + name);
                }
                else
                {
                    Response.Write("<script>alert('图片格式不正确!');</script>");
                }
        }


作者: 崔楠    时间: 2012-4-18 11:04
。。。 不知道怎么出小表情了,那个{:soso_e120:}是大写p,那个{:soso_e127:}是大写l
作者: 王雪磊    时间: 2012-4-18 13:28
{:soso_e100:}en,代码不错
作者: 鲍晨    时间: 2012-4-18 14:49
前台用 <asp:FileUpload ID="imgUpload" runat="server" Width="252px"/>
后台
            string uploadpath ="~/Admin/ImgNews/upload/";
            string filename = imgUpload.PostedFile.FileName;
            string extention = Path.GetExtension(filename);//取文件的扩展名
       string newfilename = DateTime.Now.ToString("yyyyMMddhhmmss")+extention;//定义新的名称
       string fileSavePath = uploadpath + newfilename;
            imgUpload.SaveAs(Server.MapPath(fileSavePath));




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2