仅限ASP.NET fileupload图像,在sql表中保存路径和文件名

时间:2012-09-19 09:08:15

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

  

可能重复:
  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?

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

4 个答案:

答案 0 :(得分: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.
}


    }

}

答案 1 :(得分:2)

您已从代码中发出behing问题,请尝试使用此方法验证文件名是否为某些图像。通过比较它们的扩展名。只需将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;
    }

答案 2 :(得分: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>

答案 3 :(得分: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)