I would like to display the image which i have stored as byte in Sql Table.
ItemTemplate code
ImageUrl=<%# Eval("Image")%>
Image is the byte from sql server. In my application couldn't able to show the picture from server.
SQL Schema : [Image] [image] NULL
Please suggest, how to display the image.
As if you have tried, you might have got some useful links. However here you go.
STEPS:-
1.To retreive Images from database, first you change your datatype from Image to nvarchar(550)
2.You need to write code fetching images on the basis of ID
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ImageID"] != null)
{
string strQuery = "select ImageName, ImagePath, ImageData from youtableName where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]);
DataTable dt = GetData(cmd);
if (dt != null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["ImageName"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}
GetData will be your datatable value which will be coming from the database.
To Display the image on the aspx page I have used ASP.Net Image Control refer below.
<asp:image id="Image1" runat="server" imageurl="ImageCSharp.aspx?ImageID=1" />
<asp:image id="Image2" runat="server" imageurl="ImageCSharp.aspx?ImageID=2" />
<asp:image id="Image3" runat="server" imageurl="ImageCSharp.aspx?ImageID=3" />
Here is your complete reference:-
Display Images from the database using asp.net
Related
In web application [asp.net], i am trying to get the excel data in gridview. It is working fine, but the format of the table in gridview is different from the excel. I mean format of the table is different from excel to gridivew. I am placing the screen shot please find them First is Excel Format :
second one is Gridview Screent shot which is in .aspx page.
Please help me for formating the table design. Thank you.
Try from this link: http://www.dotnetcurry.com/ShowArticle.aspx?ID=138In one video of learning Linq I saw this tag but not remember this perfectly. But I test this, also you can make table with your linq code.Have good time!
Try this code to import excel to Gridview:
using System.Data;
public partial class _Default : System.Web.UI.Page
{
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Check file is available in File upload Control
if (FileUpload1.HasFile)
{
//Store file name in the string variable
string filename = FileUpload1.FileName;
//Save file upload file in to server path for temporary
FileUpload1.SaveAs(Server.MapPath(filename));
//Export excel data into Gridview using below method
ExportToGrid(Server.MapPath(filename));
}
}
void ExportToGrid(String path)
{
OleDbConnection MyConnection = null;
DataSet DtSet = null;
OleDbDataAdapter MyCommand = null;
//Connection for MS Excel 2003 .xls format
MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path + "';Extended Properties=Excel 8.0;");
//Connection for .xslx 2007 format
// MyConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path + "';Extended Properties=Excel 12.0;");
//Select your Excel file
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
DtSet = new System.Data.DataSet();
//Bind all excel data in to data set
MyCommand.Fill(DtSet, "[Sheet1$]");
dt = DtSet.Tables[0];
MyConnection.Close();
//Check datatable have records
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
//Delete temporary Excel file from the Server path
if(System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
}
}
One of the main visible problem is your Excel spreadsheet has sub tables (for example, Cargo Qty). In 'pure' html, this can be done using COLSPAN or ROWSPAN, but with the GridView, it's not that easy, unless you create sub gridviews, like this:
<asp:GridView runat="server" ...>
<Columns>
<asp:BoundField HeaderText="MyHeader" DataField="MyField1"... />
...
<asp:TemplateField HeaderText="MySubGridHeader">
<asp:GridView runat="server" ...> // need to databind this
<Columns>
<asp:BoundField HeaderText="MySubHeader1" DataField="MyField2"... />
<asp:BoundField HeaderText="MySubHeader2" DataField="MyField3"... />
</Columns>
</asp:GridView>
</asp:TemplateField>
</Columns>
</asp:GridView>
Otherwise I suggest you go for commercial packages which can display advanced grids, such as this one for example: SPREAD (note: I'm not affiliated and I have not tested it).
It's pretty difficult to show code for ASP.NET here, so I will try my best to describe my problem.
I have a FileUploadControl and a Button that calls a function when it's clicked. It seems that the Button function works when there is nothing chosen for my FileUploadControl. However, when there is something chosen in the FileUploadControl (I have selected a file to upload), there is a problem when I click the button. It completely does not matter what the function does (it could just be writing to a label, even when it has nothing to do with the FileUploadControl). The error I get is:
This webpage is not available.
The webpage at http://localhost:2134/UploadMedia/Default.aspx might be temporarily down or it may have moved permanently to a new web address.
I have searched on Google, and people seem to have had problems with this, but different causes from me. They have said that their ASP.NET Development Server port is actually different from their port in the address bar. This is not the case for me.
Also, another problem people have had is with Use Dynamic Ports. I have tried both true and false. I have also tried different ports, and I have always gotten the same error.
This is really driving me crazy because it doesn't matter what the code in the buttonFunction is, it doesn't work as long as there is something in the FileUploadControl. If there is nothing, it seems to work fine.
Here is the code for the ASP.NET Controls:
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload" OnClick="uploadClicked" />
<br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
And this is the code for the button function:
protected void uploadClicked(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
string filename = Path.GetFileName(FileUploadControl.FileName);
//Check if the entered username already exists in the database.
String sqlDupStmt = "Select songPath from Songs where songPath ='" + Server.MapPath("~/Uploads/") + filename + "'";
SqlConnection sqlDupConn = new SqlConnection(#"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True;");
SqlCommand sqlDupCmd = new SqlCommand(sqlDupStmt, sqlDupConn);
sqlDupCmd.Connection.Open();
SqlDataReader sqlDupReader = sqlDupCmd.ExecuteReader(CommandBehavior.CloseConnection);
if (sqlDupReader.Read())
{
StatusLabel.Text = "Upload status: The file already exists.";
sqlDupReader.Close();
}
else
{
sqlDupReader.Close();
//See "How To Use DPAPI (Machine Store) from ASP.NET" for information about securely storing connection strings.
String sqlStmt = "Insert into Songs values (#songpath);";
SqlConnection sqlConn = new SqlConnection(#"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True; uid=sa; pwd=password;");
SqlCommand cmd = new SqlCommand(sqlStmt, sqlConn);
SqlParameter sqlParam = null;
//Usage of Sql parameters also helps avoid SQL Injection attacks.
sqlParam = cmd.Parameters.Add("#userName", SqlDbType.VarChar, 150);
sqlParam.Value = Server.MapPath("~/Uploads/") + filename;
//Attempt to add the song to the database.
try
{
sqlConn.Open();
cmd.ExecuteNonQuery();
FileUploadControl.SaveAs(Server.MapPath("~/Uploads/") + filename);
songList.Items.Add(filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
finally
{
sqlConn.Close();
}
}
}
}
But this buttonfunction provides the same results:
protected void uploadClicked(object sender, EventArgs e)
{
StatusLabel.Text = "FooBar";
}
Has anyone had this problem before, or might know what the cause is?
Thanks!
My friend helped me figure it out. It was because ASP.NET only allowed uploads of 4MB sizes. I had to go into the web.config or the machine.config file and change the value of MaxRequestLength to be larger than 4096. This solved it.
I trying to save employee image in employee database. I have three field in database table empid, empname, empimage. Here is my database part.
CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)
In the button click event, i have written the following code:
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);
connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(#enm, #eimg)SELECT ##IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}
And Here is my form:
<asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
<asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
<asp:FileUpload ID="imgUpload" runat="server" />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
 
<asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
<br />
<hr />
<asp:Image ID="Image1" style="width:200px" Runat="server" />
But when I am uploading any image and clicking on submit button getting this error "Object reference not set to an instance of an object." Pls somebody point out my error.
Thanks,
Sumit
Object Reference errors only occur when an object is not initialized and you try to reference it. This could be any object you are referencing within your code. If you step through the code while debugging, you can see exactly which reference is null.
You have an if statement that initializes the imgByte object:
imgByte = new Byte[File.ContentLength];
If the img object turns out to be null, that code does not run. Then you reference the imgByte here, regardless of whether or not the img was null:
cmd.Parameters.AddWithValue("#eimg", imgByte);
Check the the HttpPostedFile object itself is not null and move your imgByte object initialization outside the if statement. Also, the name File is already used by the System.IO.File object. You may want to rename it just to be safe.
I would rearrange your ADO.NET code a bit - make it safe and more reliable; also, I would make sure to separate the two SQL statements in your "sql" string by a semicolon to make it clear to SQL that this is two commands, really:
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
using(connection = new SqlConnection(conn))
{
string sqlStmt = "INSERT INTO dbo.EmpDetails(empname, empimg) " +
"VALUES(#enm, #eimg); SELECT ##IDENTITY";
using(SqlCommand cmd = new SqlCommand(sqlStmt, connection))
{
cmd.Parameters.AddWithValue("#enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#eimg", imgByte);
connection.Open();
int id = Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
lblResult.Text = String.Format("Employee ID is {0}", id);
}
}
Any luck with this?? Otherwise you should really step through the code in the debugger and see where in your code you reference something that is NULL (and you don't check for that condition).
Marc
While i am debugging this code i am
getting exception in this
line..."string conn =
ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;"
Exception is: Object reference not set
to an instance of an object.
You need to add a connection string named EmployeeConnString to web.config.
Your exception handler does not distinguish where exactly an exception occurred, and issues a single error message for any possible error.
I have a binary file which stores in the customerPicture column that has Image as a datatype in the CUSTOMERs table.
I have saved an image by using this line of code in LINQ to SQL.
Dim db = new MyCompanyDataContext
Dim newCus = new CUSTOMERs
Dim filebyte As Byte() = fileUploader.FileBytes
Dim fileBinary As New System.Data.Linq.Binary(filebyte)
newCus.customerPicture = fileBinary
Then now I want to retrieve this binary file to bind in the gridview in ASP.NET by using LINQ to SQL, but I don't know how. Can you please show me some ways to reach the solution?
you can use Httphandler to retrive the images from the database.
<ItemTemplate>
<asp:Image ID="imgPhoto" runat="server"/>
</ItemTemplate>
If you have a Image as an ItemTemplate in the datagrid.
In the ItemDataBound event of the datagrid call the "HttpHandler" to display the image.In the below code I am finding the image control and assinging the imageUrl as the HttpHandler file path.I am also passing the id as querystring to the HttpHandlerFile.
System.Web.UI.WebControls.Image photoImage = (System.Web.UI.WebControls.Image)e.Item.FindControl("imgPhoto");
photoImage.ImageUrl = "ImageHandler.ashx?PhotoID=" + id.ToString();
And in the HttpHandler file use Linq to retrive the Image and display it.
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "image/jpeg";
int photoId = -1;
//Check the query string.
if (context.Request.QueryString["PhotoId"] != null && context.Request.QueryString["PhotoId"] != "")
{
photoId = Convert.ToInt32(context.Request.QueryString["PhotoID"]);
}
if (photoId != -1)
{
MovieDataContext db = new MovieDataContext();
//Get the movie record based on the ID
MovieTable movie = db.MovieTables.First(m => m.ID == photoId);
System.Data.Linq.Binary fileBinary = movie.Photo;
byte[] fileByte = fileBinary.ToArray();
//displays the Image.
context.Response.BinaryWrite(fileByte);
}
}
As this HttpHandler file is mapped to the imageURL in the datagrid , you can see the images displayed in the datagrid.
Try this:
dim ms as new MemoryStream
ms.Write(fileBinary.ToArray(),0,fileBinary.Length)
dim img as Image
img = Image.FromStream(ms)
newCus.customerPicture = img
I am looking to fileupload a picture jpeg,gif,etc into an SQL database on an updateprofilepicture page. Then on the profile page, I want to retrieve the image from an sql database and have it show up in an Asp:Image control. I have much code trying to do this and it doesn't work. The table contains a column of type Image.
As Joel mentioned you should use an HttpHandler or a page to display the image. Here is a sample code to output image (Image.ashx) :
// ProcessRequest method of Image.ashx
long imageId = Convert.ToInt64(Request.QueryString["ImageId"]);
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(
"SELECT ImageFile FROM ImageTable WHERE ImageId = #ImageID", conn))
{
command.Parameters.Add("#ImageID", SqlDbType.Int).Value = imageId;
conn.Open();
Response.ContentType = "image/gif";
Response.BinaryWrite((byte[]) command.ExecuteScalar());
}
and then use image in your page as :
<asp:Image id="Image1" runat="server" ImageUrl="Image.ashx?ImageID=12"/>
The important thing to remember here is that you shouldn't try to transmit the image data with the profile page itself. Instead, you want your profile page to generate HTML markup for the browser that looks something like this:
<img src="~/MyImageHandler.ashx?UserID=1234" alt="User 1234 avatar" width="100px" height="150px" />
That is the ultimate result of your <asp:Image .../> control. Then the browser will send a completely separate Http request to retrieve the image. That's how pictures on web sites work. You then need to be able to handle that additional request. To do that, create an Http handler (*.ashx file) and use it to retrieve the appropriate image data from the database and send it to the browser.
If you're using SQL 2005 or greater you should not use the data type Image because it's now deprecated. Instead you want to use the new Varbinary(MAX) type if possible. Once you have it stored all you need to do is retrieve it via ADO.Net call and cast the cell value into type Byte[] and then call Response.BinaryWrite like in ScarletGarden's example above.
After a few hundred gigabytes of images, I believe you'll find yourself thinking that the operating systems' file system and static file http servers is better suited than the database, which is busy which a lot of other details, for storing images. It also allows you to use thousands of existing free tools to work with, move, host, etc the images.
Instead of storing images in the database, store the path and/or filename for the image. Images will fill up the database and make it slow.
protected void Page_Load(object sender, EventArgs e) {
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e) {
string strImageName = txtImageName.Text.ToString();
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 Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=RND3" + "\\" + "SQLEXPRESS;Initial Catalog=SSSolutionFiles;Integrated Security=True";
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Imagess(ImageName,Image)" + " VALUES (#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
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);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "File Uploaded";
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
con.Close();
}
}
Try these links it might help you..
you can also try by storing the image files on the server and store the paths on the Sql table..
by these links
http://pratikataspdotnet.blogspot.in/2014/11/retrieve-images-from-path-stored-in.html