Hello,
How can I create a file path from my web application that is locate in C:\ to look for a file and image in D:? to convert image to Bytes and save in database?
//Convert the Image to a Byte Array:
private byte[] ConvertImageToByteArray(string imagePath)
{
string fullPath = Server.MapPath("~/Images/") + imagePath;
return File.ReadAllBytes(fullPath);
}
//Save the Data into the Database:
protected void Button1_Click(object sender, EventArgs e)
{
if (!FileUpload1.HasFile) //Validation
{
Response.Write("No file Selected"); return;
}
else
{
// Read and populate textboxes from Index.txt
string indexFilePath = Server.MapPath("~/index.txt");
PopulateTextBoxes(indexFilePath);
// Extract values from textboxes
string acctNumber = txtAcctNumber.Text;
string chkNumber = txtChkNumber.Text;
string imgDate = txtDate.Text;
string imagePath = ViewState["ImagePath"].ToString();
// Convert the image to byte array
byte[] imageData = ConvertImageToByteArray(imagePath);
// Insert the data into the database
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
{
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO chkImages (acctNumber, chknumber, imgdate, imageData) VALUES (@acctNumber, @chknumber, @imgdate, @imageData)", connection);
cmd.Parameters.AddWithValue("@acctNumber", acctNumber);
cmd.Parameters.AddWithValue("@chknumber", chkNumber);
cmd.Parameters.AddWithValue("@imgdate", imgDate);
cmd.Parameters.AddWithValue("@imageData", imageData);
cmd.ExecuteNonQuery();
connection.Close();
Response.Write("Image has been Added");
}
}
}
Asma KhalidPosted Jul 18, 2024, 3:38 AM
In web applications files accessiblibity are usually based on server URLs and not disks. So, if you want to access server file/image from the browser then the path of image must be accessible via URL. This means that behind on the server your Web app has a content folder on the similar disk where your app is deployed unless you have configured the location of the content folder specifically at different disk (not recommended normally). But, server-side may access the internal disks absolute paths, but the browser accessible file must be copied to the content folder otherwise your browser won't recofnize the path as URL path.
Thats why file/img is either stored into databse and bytes are accessed or into the web app content folder so, it is accessible via URL.
Look into below tutorials for more details about storing/accessing file from either database or from web app content folder i .e.
Upload File into Database: https://bit.ly/2AoN6DZ
Upload File as File on Server: https://bit.ly/2BySQM9
I hope this helps.
Prasad RaveendranPosted Jul 16, 2024, 11:53 PM
To make the path configurable, you can store the path in your application's configuration file (e.g.,
web.configorappsettings.json). This way, you can easily change the path without modifying the code. Below, I'll demonstrate how to do this usingweb.configas an example.