5

Possible Duplicate:
How to restrict file type in FileUpload control

I have a problem, using my image uploader. It will upload all type of files. I need code behind, to sort out if it's an image (jpg, png and so on). Then it needs to save the path and filename in my sql. Saving name and path is up and running, so is the regular expression. I now need to incorporate som code that i have found here. The question is, how it's done?

My code behind is:

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();
        }
    }
}

I need to put that code inside the following code, that I have found here. How can i upload only jpeg files?

Do I place my code after the code from here, or were do I place it? Please help.

Community
  • 1
  • 1
Anders
  • 103
  • 1
  • 3
  • 10

4 Answers4

2

you have asked from code behing so Try this method to validate your file names if they are some image or not. by comparing their extensions.. Just pass your FileUplaod control's name to this method and validate your Button's 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 Pathak
  • 3,621
  • 5
  • 39
  • 67
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.
}


    }

}
Kapil Khandelwal
  • 15,958
  • 2
  • 45
  • 52
1

I found a solution with this workaround:

<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>
Emanuele Greco
  • 12,551
  • 7
  • 51
  • 70
0

Here is regex for you..

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)
Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49