上传图片

上传图片
aspx前端:

<div>
    <asp:Image ID="Image1" runat="server" />//这个控件在浏览器中不显示 <span style="color:#eeff00">图片预览</span>
    <asp:TextBox ID="txtCover" runat="server" ReadOnly=“true”></asp:TextBox>//显示存储图片的路径 
    <span style="color:#4cff00">图片上传的路径</span> </br>
    <asp:FileUpload ID="imgupload" runat="server" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Button ID="btnUpload" runat="server" Text="上传" OnClick="btnUpload_Click" /> 
   //OnClick是鼠标点击跳转的事件 btnUpload_Click 是执行protected void btnUpload_Click(object sender, EventArgs e)这个事件 
</div>

aspx.cs后台

protected void btnUpload_click(object sender, EventArgs e)
{
    if(imgupload.PostedFile.FileName != "")
    {
        string imgPath = imgupload.PostedFile.FileName;
        string extPath = imgPath.Substring(imgPath.LastIndexOf(".") + 1)
        if(extPath.ToLower() != "jpg" && extPath.ToLower() != "png" && extPath.ToLower() != "bmp")
        {
            Page.ClientScript.RegisterClientScriptBlock(GetType(), "", "<script language=javascript>alert('选择文件类型JPG,bmp,PNG')</script>");
        }
        else
        {
            string sPath = Server.MapPath("/UploadFiles/upload");
            imgupload.PostedFile.SaveAs(sPath + "\\" + imgPath.Substring(imgPath.LastIndexOf("\\") + 1); 
sPath = sPath.Substring(sPath.LastIndexOf("\\") + 1); //sPath = 文件夹里的upload; //在这里Spath被重置为\\upload this.txtCover.Text = sPath + "/" + imgPath.Substring(imgPath.LastIndexOf("\\") + 1); //文件夹里的upload+xx.jpg; // 这里txtCover的值为upload文件名.扩展名 Page.ClientScript.RegisterClientScriptBlock(GetType(), "", "<script language=javascript>alert('上传成功')</script>");
Image1.ImageUrl = "/UploadFiles/" + this.txtCover.Text; //?upload/$@B0)U`]TDA@MKRDW15BJQR.jpg } else { Page.ClientScript.RegisterClientScriptBlock(GetType(), "", "<script language=javascript>alert('请选择图片')</script>"); } } }

 

posted @ 2018-01-15 21:36  ProZkb  阅读(198)  评论(0编辑  收藏  举报