【问题标题】:ASP.NET fileupload images only, saving path and filename in sql table [duplicate]仅 ASP.NET 文件上传图像,将路径和文件名保存在 sql 表中 [重复]
【发布时间】:2012-09-11 13:53:29
【问题描述】:

可能重复:
How to restrict file type in FileUpload control

我在使用图片上传器时遇到了问题。它将上传所有类型的文件。 我需要后面的代码,以确定它是否是图像(jpg、png 等)。 然后它需要将路径和文件名保存在我的sql中。 保存名称和路径已启动并正在运行,正则表达式也是如此。我现在需要合并我在这里找到的 som 代码。问题是,它是怎么做到的?

我的代码是:

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (FileUpload1.PostedFile != null)
    {
        string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

        //Save files to disk
        FileUpload1.SaveAs(Server.MapPath("~/_PublicData/Images/" + FileName));

        //Add Entry to DataBase
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Computer_Klubben_CommunitySiteConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        string strQuery = "insert into dbo.Billeder (FileName, FilePath)" + " values(@FileName, @FilePath)";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.AddWithValue("@FileName", FileName);
        cmd.Parameters.AddWithValue("@FilePath", "~/_PublicData/Images/" + FileName);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;

        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

        finally
        {
            con.Close();
            con.Dispose();
        }
    }
}

我需要将该代码放入我在此处找到的以下代码中。 How can i upload only jpeg files?

我是把我的代码放在这里的代码之后,还是我把它放在了? 请帮忙。

【问题讨论】:

    标签: c# asp.net file-upload code-behind


    【解决方案1】:

    我找到了一个解决方法:

    <asp:FileUpload ID="fuImportImage" runat="server" />
    <asp:RegularExpressionValidator ID="regexValidator" runat="server"
         ControlToValidate="fuImportImage"
         ErrorMessage="Only JPEG images are allowed" 
         ValidationExpression="(.*\.([Jj][Pp][Gg])|.*\.([Jj][Pp][Ee][Gg])$)">
    </asp:RegularExpressionValidator>
    

    【讨论】:

      【解决方案2】:

      您已从代码行为中询问,因此请尝试使用此方法来验证您的文件名是否是某些图像。通过比较它们的扩展名.. 只需将您的 FileUplaod 控件的名称传递给此方法并验证您的 Button 的 Click..

        private Boolean ImageUploadValidation(FileUpload UploadedFile)
      {
          String FileExtension = String.Empty, Code = String.Empty;
          try
          {
              if (String.IsNullOrEmpty(UploadedFile.PostedFile.FileName))
              {
                  Code = "<script> alert(' Please select file');</script>";
                  ClientScript.RegisterStartupScript(this.GetType(), "someKey", Code);
                  return false;
              }
      
              FileExtension = Path.GetExtension(UploadedFile.FileName).ToLower();
      
              if (!FileExtension.Equals(".gif") &&
                  !FileExtension.Equals(".png") &&
                  !FileExtension.Equals(".jpg") &&
                  !FileExtension.Equals(".bmp") &&
                  !FileExtension.Equals(".gif") &&
                  !FileExtension.Equals(".jpeg") &&
                  !FileExtension.Equals(".tif") &&
                  !FileExtension.Equals(".tiff"))
              {
                  Code = "<script> alert(' Please select valid file. File can be of extension(gif, png, jpg, bmp, gif, jpeg, tif, tiff)');</script>";
                  ClientScript.RegisterStartupScript(this.GetType(), "someKey", Code);
                  return false;
              }
              return true;
          }
          catch (Exception)
          {
      
              throw;
          }
      

      【讨论】:

      • 对不起,我错误地编辑了你的代码,我认为那是我的
      • 如何回滚我的编辑,再次抱歉,因为我提交了答案,我希望修改我的答案
      • 没关系..我再次编辑了代码.. :)
      • 我很高兴你解决了编辑谢谢 Mayank
      【解决方案3】:
      protected void btnUpload_Click(object sender, EventArgs e)
      {
          if (FileUpload1.PostedFile != null)
          {
                  string fileExt = 
                     System.IO.Path.GetExtension(FileUpload1.FileName);
      
                  if (fileExt == ".jpeg" || fileExt == ".jpg")
                  {
      
      string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
      
              //Save files to disk
              FileUpload1.SaveAs(Server.MapPath("~/_PublicData/Images/" + FileName));
      
              //Add Entry to DataBase
              String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Computer_Klubben_CommunitySiteConnectionString"].ConnectionString;
              SqlConnection con = new SqlConnection(strConnString);
              string strQuery = "insert into dbo.Billeder (FileName, FilePath)" + " values(@FileName, @FilePath)";
              SqlCommand cmd = new SqlCommand(strQuery);
              cmd.Parameters.AddWithValue("@FileName", FileName);
              cmd.Parameters.AddWithValue("@FilePath", "~/_PublicData/Images/" + FileName);
              cmd.CommandType = CommandType.Text;
              cmd.Connection = con;
      
              try
              {
                  con.Open();
                  cmd.ExecuteNonQuery();
              }
      
              catch (Exception ex)
              {
                  Response.Write(ex.Message);
              }
      
              finally
              {
                  con.Close();
                  con.Dispose();
              }
      
      
      }
      else
      {
        //Show Error Message. Invalid file.
      }
      
      
          }
      
      }
      

      【讨论】:

      • 我也是这么想的……我现在就试试。
      • 谢谢....我必须先听听如何制作论坛。我的老师首先要引起我的注意。这就是我想要的。再次感谢。
      【解决方案4】:

      这是给你的正则表达式..

      System.Text.RegularExpressions.Regex imageFilenameRegex = new 
      System.Text.RegularExpressions.Regex(@"(.*?)\.(jpg|jpeg|png|gif)$", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase);
      
      
      bool ismatch =imageFilenameRegex.IsMatch(imgFile.FileName)
      

      【讨论】:

        猜你喜欢
        • 2018-02-22
        • 2020-06-23
        • 2019-02-19
        • 2012-08-26
        • 1970-01-01
        • 1970-01-01
        • 2016-04-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多