asp.net upload an image - c#

I have an asp.net web forms site, I am looking to create a control that allows the user to browse for an image then save the image into the database. I know that saving images into a database is bad practice, but thats what I've been told to do!
Does anyone have any suggestions for the best approach to do this?
thanks

Essentially all you need is a FileUpload control and some code to save it to the database. (And you'll want to do some input checking as well, naturally.) There's a pretty old tutorial which explains the concept well here. This one is a little more recent. But there's no shortage of others.

from a sample:
var intDoccumentLength = FileUpload1.PostedFile.ContentLength;
var newDocument = new byte[intDoccumentLength];
var stream = FileUpload1.PostedFile.InputStream;
stream.Read(newDocument, 0, intDoccumentLength);
var sqlConnection = new SqlConnection(sqlConnectionString);
sqlConnection.Open();
var sqlQuery = "INSERT INTO dbo.DocumentData (DocName, DocBytes, DocData, DocCreatedAt) VALUES (#DocName, #DocBytes, #DocData, #DocCreatedAt);"
+ "SELECT CAST(SCOPE_IDENTITY() AS INT)";
sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlCommand.Parameters.Add("#DocName", SqlDbType.NVarChar, 255);
sqlCommand.Parameters.Add("#DocBytes", SqlDbType.Int);
sqlCommand.Parameters.Add("#DocData", SqlDbType.VarBinary);
sqlCommand.Parameters.Add("#DocCreatedAt", SqlDbType.DateTime);
sqlCommand.Parameters["#DocName"].Value = FileUpload1.PostedFile.FileName;
sqlCommand.Parameters["#DocBytes"].Value = intDoccumentLength;
sqlCommand.Parameters["#DocData"].Value = newDocument;
sqlCommand.Parameters["#DocCreatedAt"].Value = DateTime.Now;
var newDocumentId = (Int32) sqlCommand.ExecuteScalar();
sqlConnection.Close();

There is fileupload tool available in toolbox. You just have to writ the below code in the click event of button..
string filename = FileUpload1.FileName.ToString();
if (filename != "")
{
ImageName = FileUpload1.FileName.ToString();
ImagePath = Server.MapPath("Images");
SaveLocation = ImagePath + "\\" + ImageName;
SaveLocation1 = "~/Image/" + ImageName;
sl1 = "Images/" + ImageName;
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
and I hope you have an image column in your database so then just insert the string sl1 in your insert query..

Related

Loading Image through label

I am trying to load an image through label using this code
private void getData()
{
SqlConnection conn = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
conn.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT empName,empLname,empMi,empImage
FROM employees
WHERE empName = '"+ ddlAvail.SelectedItem.Value.ToString() +"'", conn);
SqlDataReader rdr = sqlCmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
lblName.Text = rdr.GetValue(0).ToString();
lblLname.Text = rdr.GetValue(1).ToString();
lblMi.Text = rdr.GetValue(2).ToString();
lblImage.Text = "<img runat='server' src='" + rdr.GetValue(3).ToString() + "'></img>";
}
}
conn.Close();
}
every time I select a dropdownlist value it generates me set of sql data.My only problem is the image.Cause it wont load any image at all.The filepath on my visual studio and image name is correct.
This is an example of my image
../Images/Profile/logo.jpg
I save the images filepath on my database.
Your code looks fine
Make sure the file path your are retrieving from the database exists and the path isn't returning any unwanted characters.
That is:
rdr.GetValue(3).ToString() //should return the right path (string)
It should be fine. Hope this helped
It won't ever show the image because all that your code is doing is setting the text on the label.
If you want to display the image try this , or this.

Delete the old image when it has to upload new image

this is so that when I need to upload a right an image to an article so it must delete the old image
and it must be clear in the folder where the image is located,
string Tid = DateTime.Now.Ticks.ToString();
string unikID = Guid.NewGuid().ToString();
string url = "~/img/bimg/";
cmd.CommandText = "SELECT img FROM aktiviteter WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
conn.Open();
SqlDataReader readerImg = cmd.ExecuteReader();
if (readerImg.Read())
{
File.Delete(Server.MapPath(url.Remove(0, 1) + readerImg["img"]));
}
conn.Close();
problem is that I need to find the image in the column in the database where the entity who should delete the picture
Access to the path 'C:\Users\198407\Documents\Visual Studio 2013\WebSites\Jesper-mm-CRUD\img\bimg\' is denied.
my pictures located here: /img/bimg/hello.png
how it looks when I load to the server
string Tid = DateTime.Now.Ticks.ToString();
string unikID = Guid.NewGuid().ToString();
string url = "~/img/bimg/";
cmd.CommandText = "SELECT img FROM aktiviteter WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
conn.Open();
SqlDataReader readerImg = cmd.ExecuteReader();
if (readerImg.Read())
{
File.Delete(Server.MapPath(url.Remove(0, 1) + readerImg["img"]));
}
conn.Close();
ImageNet.FluentImage img = ImageNet.FluentImage.FromStream(FileUploadImg.FileContent);
img.Resize.Scale(360).Save(Server.MapPath(url + unikID + ".png"));
if (File.Exists(Server.MapPath(url + unikID + ".png")))
{
cmd.CommandText = "UPDATE aktiviteter SET navn = #navn, sted = #sted, indhold = #indhold, img = #img, rubrik = #rubrik, retbrugerID = #retbrugerid WHERE Id = #id;";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#navn", navn);
cmd.Parameters.AddWithValue("#sted", Sted);
cmd.Parameters.AddWithValue("#indhold", Indhold);
cmd.Parameters.AddWithValue("#img", unikID);
cmd.Parameters.AddWithValue("#rubrik", rubrik);
cmd.Parameters.AddWithValue("#retbrugerid", brugerid);
}
Since you are getting this error -
Access to the path 'C:\Users\198407\Documents\Visual Studio
2013\WebSites\Jesper-mm-CRUD\img\bimg\' is denied.
I would suggest , granting read/write access to this user = IIS_IUSRS for required directory.
Read more helpful link

Not getting image in Image Control by Url in asp.net

Hello Friends i am storing an image via URL in database but when i retrieve it on Image Control of asp.net it doesn't show the image please help
Profile.aspx.cs
con.Open();
string str = "SELECT * FROM [aspdotnetpractice].[dbo].[Users] where Username ='" + lblHowdy.Text + "'";
SqlCommand com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
Image1.ImageUrl = Server.MapPath(reader[8].ToString());
Label1.Text = reader[1].ToString();
Label2.Text = reader[2].ToString();
Label3.Text = reader[3].ToString();
Label4.Text = reader[6].ToString();
Label5.Text = reader[4].ToString();
reader.Close();
con.Close();
}
Make sure you save path value like "ImageFiles/test.jpg" or filename only like "test.jpg". Dont save to path field a complete local path like "c:\…\test.jpg". In imageurl you should use virtual path instead physical path.
The Server.MapPath returns a file name. On the other hand, Image.ResolveUrl expects a valid url.
You'd rather want something like
Image1.ImageUrl = Page.ResolveUrl("~/ImageFiles/") + fi.Name; // You just need to pass name or something similar.

Saving multiple Images at once to the database with a FileUpload Control

I am working on a company Blog site, and when a user is making a post, they can add an image from their computer to the post. I used a FileUpload control to do this, and it works great. However, I am trying to change the functionality to allow the user to select and upload multiple images in one post, and I am running into some issues. I have set the 'allow multiple' property to 'true', however once multiple images are selected into the control (Image URLs get separated by a comma) and the post button is clicked, only one of the images is inserted into the database, but it is inserted as many times as images there are, and only that one image is displayed on the blog post. So if I try to add three different images, it inserts three instances of the first image into the database. The code corresponding to the the FileUpload in my onClick function is below:
if (imageUpload.HasFile == true)
{
SqlCommand maxMessId = new SqlCommand("SELECT Max(MessageID) FROM BlogMessages", conn);
lastMessageID = Convert.ToInt32(maxMessId.ExecuteScalar());
foreach (var uploadedFile in imageUpload.PostedFiles)
{
SqlCommand cmdInsertImage = new SqlCommand("INSERT INTO BlogImages(Image, MessageID) VALUES (#Image, #MessageID)", conn);
cmdInsertImage.Parameters.AddWithValue("#Image", SqlDbType.Image).Value = imageUpload.FileBytes;
cmdInsertImage.Parameters.AddWithValue("#MessageID", lastMessageID);
cmdInsertImage.ExecuteNonQuery();
}
}
I am thinking the issue could be with:
cmdInsertImage.Parameters.AddWithValue("#Image", SqlDbType.Image).Value = imageUpload.FileBytes;
If that is getting the file bytes for only one image.. I am not sure how to get the filebytes for both files. The image column in my BlogImages table is of the type Image.
Any suggestions are much appreciated!
Are you sure that you're working on the right way ?????PostesFiles are the list of file and each one has it own properties you need to read from there.....nothing else
Here a simples examples
For Each xx In fp.PostedFiles
xx.InputStream
xx.ContentLength
xx.FileName
Next
Where those properties upon expose Inputstrem a stream of the image,ContenteLenght it lenght, Filename the filename of the images.So when you pass the imageupload.FileBytes is not the correct way to achive your goal.You have to read the stream and return a bytearray to save the data withing your sql server.Nothing else i hope it could help you to solve your issue.
UPDATE*
Assume that you're into the foreach loop for each single file you have to setup its own bytearray
MemoryStream ms = new MemoryStream();
file.PostedFile.InputStream.CopyTo(ms);
var byts = ms.ToArray();
ms.Dispose();
then
change your insert statement like this
cmdInsertImage.Parameters.AddWithValue("#Image", SqlDbType.Image).Value = byts;
not tested but it should solve the issue.
UPDATE 2
if (test.HasFiles) {
StringBuilder sb = new StringBuilder();
foreach (void el_loopVariable in test.PostedFiles) {
el = el_loopVariable;
sb.AppendLine("FILENAME:<B>" + el.FileName.ToString + "</B><BR/>");
MemoryStream ms = new MemoryStream();
el.InputStream.CopyTo(ms);
byte[] byts = ms.ToArray;
ms.Dispose();
sb.AppendLine(string.Join(";", byts));
sb.AppendLine("<br/<br/>");
byts = null;
}
LitResponse.Text = sb.ToString;
}
I think the issue is that in your for each loop, you're stepping through the posted files, but you're still just using ImageUpload.FileBytes each time, which I expect would be returning the same thing each time.
I'm not super familiar with the file upload control, but maybe you can use the ContentLength property of your uploaded file object to index into the byte array returned by ImageUpload.FileBytes (assuming that array contains each of the multiple files).
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strImageName = txtImage.Text.ToString(); //to store image into sql database.
if (FileUpload1.PostedFile != null &&
FileUpload1.PostedFile.FileName != "")
{
byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Pictures(ID,ImageName,Image)" +
" VALUES (#ID,#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
//retrieve latest ID from tables which was stored in session.
int ID = Convert.ToInt32(System.Web.HttpContext.Current.Session["ID"].ToString());
SqlParameter ID = new SqlParameter
("#ID", SqlDbType.Int, 5);
ID.Value = (Int32)ID;
cmd.Parameters.Add(ID);
SqlParameter ImageName = new SqlParameter
("#ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter("#Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
lblMessage.Text = "File Uploaded";
lblSuccess.Text = "Successful !";
}}

upload new file first check if this file exist already in database or not then if not exist save that in database

I'm trying to create sql database that contains
Image Id (int)
Imagename (varchar(50))
Image (image)
and in aspx write in upload button this code:
protected void btnUpload_Click(object sender, EventArgs e)
{
//Condition to check if the file uploaded or not
if (fileuploadImage.HasFile)
{
//getting length of uploaded file
int length = fileuploadImage.PostedFile.ContentLength;
//create a byte array to store the binary image data
byte[] imgbyte = new byte[length];
//store the currently selected file in memeory
HttpPostedFile img = fileuploadImage.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename = txtImageName.Text;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)", connection);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
When I'm uploading a new image I need to first check if this image already exists in database and if it doesn't exist save that in database.
Please how I can do that?
Add a method that is responsible for checking if the filename already exists in the table.
private bool FileExists(string imageName)
{
using (SqlConnection conn = new SqlConnection()) // establish connection
{
using (SqlCommand cmd =
new SqlCommand("select 1 where exists(select Id from Image where ImageName = #)", conn))
{
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imageName;
return cmd.ExecuteNonQuery() > 0;
}
}
}
Then I would call this like so
if (fileuploadImage.HasFile && !FileExists(txtImageName.Text))
{
...
string cmd ="if not exists (select * from Image where ImageName= #imagename); ";
\\if you want to check image data
\\ (select * from Image where SUBSTRING(ImageName, 1, 8000)= SUBSTRING(#imagename, 1, 8000) );
string cmd += "INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";
SqlCommand cmd = new SqlCommand(cmd, connection);
If you want to verify imagedata, You can try to use DATALENGTH as first line of check for the two images.
If the DATALENGTH is different, then you suppose to have a "different" picture".
You can also use SUBSTRING(Image, 1, 8000) to check first 8000 bytes.
And also SUBSTRING(Image, DATALENGTH(Image) - 7999, 8000) to check last 8000 bytes.
One of the fastest ways is to do an UPDATE and then INSERT if update returns no updates.
string cmd = #"UPDATE Image SET Image = #imagedata WHERE ImageName = #ImageName
IF ##ROWCOUNT=0
INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";
Or if query on Image itself:
string cmd = #"UPDATE Image SET ImageName = #ImageName WHERE Image = #imagedata
IF ##ROWCOUNT=0
INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)";

Categories

Resources