Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrong image path save in sql

Tags:

c#

sql

asp.net

i am new to asp.net c# somehow i am able to save image in folder and it's path in sql, but the code is saving the full path which is incorrect.enter image description here

below is the sql table picture.

my code is

con.Open();
if (Image.HasFile) {
    string filename = Path.GetFileName(Image.PostedFile.FileName);
    String ext = System.IO.Path.GetExtension(Image.FileName);
    string filesize = Image.FileBytes.Length.ToString();

    if (ext.ToLower() == ".JPG" || ext.ToLower() == ".jpg" || ext.ToLower() == ".PNG" || ext.ToLower() == ".png" || ext.ToLower() == ".GIF" || ext.ToLower() == ".gif") {
        string filepath = Server.MapPath("~/Posts/") + filename;
        Image.SaveAs(filepath);
        string qry1 = "insert into Images(Image_Name,Image_Size,Image_Path)values('" + filename + "','" + filesize + "','" + filepath + "')";
        SqlCommand cmmd = new SqlCommand(qry1, con);
        cmmd.ExecuteNonQuery();
    } else if (ext.ToLower() == ".mp4" || ext.ToLower() == ".MP4" || ext.ToLower() == ".mpeg" || ext.ToLower() == ".MPEG" || ext.ToLower() == ".AVI" || ext.ToLower() == ".avi") {
        string filepathv = Server.MapPath("~/Posts/videos/" + filename);
        Image.SaveAs(filepathv);
        string qry1 = "insert into videos(Video_Name,Video_Size,Video_Path)values('" + filename + "','" + filesize + "','" + filepathv + "')";
        SqlCommand cmmd = new SqlCommand(qry1, con);
        cmmd.ExecuteNonQuery();
    }
}
like image 922
msz Avatar asked Mar 16 '26 19:03

msz


1 Answers

First, use SqlParamter to avoid Sql injection, you should find a lot about this on stackoverflow: How does SQLParameter prevent SQL Injection?

Second, Server.MapPath returns the complete mapped file path, absolute to your hosting enviornment. It seems that you currently host every thing in an IIS Express (starting the project with F5/Start). To get the relative path you need the path of the base directory for your images/videos. Take a look at How to get relative path from absolute path. You only need to specify your working directory. For example C:\inetpub\your-project\. Hope this helps.

EDIT If you want to use your working directory for calculating a relative path, try to use: Environment.CurrentDirectory

like image 55
BendEg Avatar answered Mar 18 '26 09:03

BendEg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!