C# ASP.NET 文件只上传图片,在sql表中保存路径和文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12491608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:26:19  来源:igfitidea点击:

ASP.NET fileupload images only, saving path and filename in sql table

c#asp.netfile-uploadcode-behind

提问by Anders

Possible Duplicate:
How to restrict file type in FileUpload control

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

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?

我有一个问题,使用我的图片上传器。它将上传所有类型的文件。我需要背后的代码,以找出它是否是图像(jpg、png 等)。然后它需要在我的sql中保存路径和文件名。保存名称和路径已启动并正在运行,正则表达式也是如此。我现在需要合并我在这里找到的一些代码。问题是,它是如何完成的?

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?

我需要将该代码放入我在这里找到的以下代码中。 如何只上传jpeg文件?

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

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

采纳答案by Kapil Khandelwal

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.
}


    }

}

回答by Emanuele Greco

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>

回答by Mayank Pathak

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..

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

回答by Anant Dabhi

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)