コード例 #1
0
    public void UploadButton_Click(object sender, EventArgs e)
    {
        string username = Session["username"].ToString();
        string userid   = Session["userid"].ToString();

        try
        {
            if (FileUploadControl.HasFile)
            {
                string filename = Path.GetFileName(FileUploadControl.FileName);

                if (Usr.extensions.Any(filename.Contains))
                {
                    System.Drawing.Image img = System.Drawing.Image.FromStream(FileUploadControl.PostedFile.InputStream);
                    int fileHeight           = img.Height;
                    int fileWidth            = img.Width;
                    if (fileHeight > Usr.maxImgHeight || fileWidth > Usr.maxImgWidth || FileUploadControl.PostedFile.ContentLength > 3000000)
                    {
                        zlyImg.Text = "zły rozmiar pliku (max: " + Usr.maxImgHeight + "px/" + Usr.maxImgWidth + "px";
                        return;
                    }

                    string strPath = "gallery\\" + username;

                    //Check if the Upload directory exists in the given path
                    bool dirExists = Directory.Exists(Server.MapPath("./") + strPath);
                    //If the directory does not exist, Create it.
                    if (!dirExists)
                    {
                        Directory.CreateDirectory(Server.MapPath("./") + strPath);
                    }

                    string savePath = Server.MapPath("./") + strPath + "\\" + filename;

                    bool updated = Usr.SaveFileToDatabase(userid, strPath + "\\" + filename, false);

                    if (updated)
                    {
                        FileUploadControl.SaveAs(Server.MapPath("./") + strPath + "\\" + filename);
                    }
                    else
                    {
                        zlyImg.Text = "Plik o tej samej nazwie znajduje sie już w bazie";
                    }
                }
                else
                {
                    zlyImg.Text = "Niedozwolone rozszerzenie pliku (dozwolone są: jpg, gif, png)";
                }
            }
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }