5

可能重复:
如何在 FileUpload 控件中限制文件类型

我有一个问题,使用我的图片上传器。它将上传所有类型的文件。我需要后面的代码,以确定它是否是图像(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();
        }
    }
}

我需要将该代码放入我在此处找到的以下代码中。 我怎样才能只上传jpeg文件?

我是在此处的代码之后放置我的代码,还是放置它?请帮忙。

4

4 回答 4

2

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

  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;
    }
于 2012-09-19T09:13:52.830 回答
2
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.
}


    }

}
于 2012-09-19T09:14:58.803 回答
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>
于 2012-09-19T09:12:52.680 回答
0

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

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)
于 2012-09-19T09:17:50.733 回答