关于C#服务器控件FileUpload上传图片并保存到数据库

来源:互联网 发布:古代疆域图软件 编辑:程序博客网 时间:2024/06/06 09:46

// 使用js-alert()弹出消息
public static void Show(Page page, string msg)
{
        page.ClientScript.RegisterStartupScript(page.GetType(), "message", "<script language='javascript' defer>

                                                               alert(/"" + msg.ToString() + "/");</script>");
}

 

// 输入完整的路径,进行删除文件操作
public void DeleteFile(string filePath)
{
      if (File.Exists(filePath))
      {
            File.Delete(filePath);
      }
}

 

    /// <summary>
    /// 检测文件上传格式(防止在地址栏输入错误的链接)
    /// </summary>
    /// <param name="hifile"></param>
    /// <returns></returns>
    public static bool IsAllowedExtension(FileUpload hifile)
    {
        System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, System.IO.FileMode.Open, 

                                                                                     System.IO.FileAccess.Read);

        System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
        string fileclass = "";
        byte buffer;
        try
        {
            buffer = r.ReadByte();
            fileclass = buffer.ToString();
            buffer = r.ReadByte();
            fileclass += buffer.ToString();
        }
        catch { }
        r.Close();
        fs.Close();

        //255216是jpg;7173是gif;6677是BMP;13780是PNG;7790是exe,8297是rar
        //JPG = 255216,GIF = 7173,PNG = 13780,SWF = 6787,RAR = 8297,ZIP = 8075,_7Z = 55122,255216 jpg;,
        //7173 gif;,6677 bmp,13780 png;,6787 swf,7790 exe dll,8297 rar,8075 zip,55122 7z,6063 xml,6033 html,
        //239187 aspx,117115 cs,119105 js,102100 txt,255254 sql ,
        //jpg,gif,BMP,PNG,mp3,wma,rm
        if ("255216,7173,6677,13780".IndexOf(fileclass) != -1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

 
    //上传文件到服务器

    public bool FileUploadU(string savePath, FileUpload fileupload, out string result)
    {
        //从web.config中读取上传路径 ConfigurationManager.ConnectionStrings["path"].ConnectionString
        string path = "";
        try
        {
            //获取文件后缀名
            int last = fileupload.PostedFile.FileName.LastIndexOf(".");
            //获取指定路径的文件名
            string fileExtension = fileupload.PostedFile.FileName.Substring(last + 1);
            if (IsAllowedExtension(fileupload) == true)
            {
                //上传文件后缀名
                fileExtension = fileupload.PostedFile.FileName.Substring(last);
                path = Helper.DateAsfileName() + fileExtension;

                result = savePath + path;
                //int start=result.Substring
                result = result.Substring(0, result.LastIndexOf("//"));

                //上传到服务器后的物理路径(实际路径)
                if (!Directory.Exists(result))
                {
                    Directory.CreateDirectory(result);
                }
                result = path;
                fileupload.PostedFile.SaveAs(savePath + result);
            }
            else
            {
                result = "文件上传格式不正确!";
                return false;
            }
        }
        catch (Exception ex)
        {
            result = "文件上传错误:/r/n" + ex.Message + " 出错位置:/r/n" + ex.StackTrace;
            return false;
        }
        return true;
    }

 

    protected void btnOk_Click(object sender, EventArgs e)
    {
        btnList.Visible = true;
        pnlQuery.Visible = true;
        pnlModify.Visible = false;

        try
        {
            int count;
            SqlParameter[] parm = new SqlParameter[8];
            string picPath = (string)ViewState["Pic"];
            parm[0] = new SqlParameter("@RecordID", SqlDbType.Int);
            parm[0].Value = txtRecordID.Text;
            if (!string.IsNullOrEmpty(picPath) && deletePhoto.Checked)
            {
                DeleteFile(Server.MapPath("~/") + @"Res/MusicAlbum" + picPath);
            }
            string strPicFileName = string.Empty;
            if (FileUploadU(MapPath("~/") + @"Res/MusicAlbum/", fuPic, out strPicFileName))
            {
                try
                {
                    parm[1] = new SqlParameter("@Pic", @"/" + strPicFileName);
                    parm[2] = new SqlParameter("@Title", txtTitle.Text);
                    parm[3] = new SqlParameter("@SingerName", txtSingerName.Text);
                    parm[4] = new SqlParameter("@VisitorCount", txtVisitCount.Text);
                    parm[5] = new SqlParameter("@CreatePeople", txtCreateDate.Text);
                    parm[6] = new SqlParameter("@EditPeople", txtEditPeople.Text);
                    parm[7] = new SqlParameter("@EditDate", DateTime.Now);

                    count = Conn.RunProcedure("MIndex2NAHotAlbumLarge_Update", parm, out count);
                    Common.Show(this, "编辑成功!");
                    bindAlbumHot();
                }
                catch (SqlException ex)
                {
                    string strErrorMsg = "编辑失败,错误信息:" + ex.Message + " 出错位置: " + ex.StackTrace;
                    Show(this, strErrorMsg.Replace("/r", "
//r").Replace("/n", "//n"));
                }
            }
            else
            {
                Show(this, "上传失败,请重新上传!");
            }
        }
        catch (Exception ex)
        {
            string strErrorMsg = "操作出错,错误信息:" + ex.Message + " 出错位置: " + ex.StackTrace;
            Show(this, strErrorMsg.Replace("/r", "
//r").Replace("/n", "//n"));
        }
    }

原创粉丝点击