Jsp mysql insert image to database

hi all
my qry is this
i have a register page and wish to give the user the option to upload there picture but i dont know quite how this is done
i can insert all the rest of the data to my database am just unsure on the inserting of the image file
can anybody help me out?
thanks

hi annie
could you explain more.. i dont know what or how a
blob field is
thanksBLOB is Binary Large OBject field. You can store an image as binary data in such a field. Check this link for some code help:
http://www.theserverside.com/discussions/thread.tss?thread_id=7401
Annie.

Similar Messages

  • Inserting image in database

    i want to insert a image in database(mysql) using servlet/jsp.
    please help me out

    try it using file IO. when the file is read and store that in object and then try to insert

  • Inserting Images in Database

    Hi,
    I am using forms6 and database is 8.0.5. I have images stored in a folder say c:\images\. I have a table for item master and the item code is same as the image name in the image folder. Eg : Item code -ABC123 so there is a image jpeg format by the name ABC123. All the records are created in item master.
    Now if the user puts 10 images in this folder i want to read all this images and insert it in item master against this item code. Now i want to know the sql for this
    1>Reading sequentially all the images from this folder
    2>By the image file name read the itemcode from the item master and insert image in that record. I am using Long raw for storing the images.
    Thanks in advance.

    Hi,
    I managed reading the images from the folder and but just stuck up with the problem.
    Test -1
    I declared a variable var_abc long raw.
    read_image_file(v_filename,'ANY',var_abc);
    update item_master set item_pict = var_abc where item_code = var_item;
    Here it gives error at runtime on read_image_file for var_abc
    Test-2
    I created a nondatabase block and create a column txt_image with type as image.
    read_image_file(v_filename,'ANY',:txt_image);
    update item_master set item_pict = :txt_image where item_code = var_item;
    Here it gives error at compilation on item_pict =:txt_image
    Anyone can help me out where i am making mistake ?.

  • INSERTING IMAGE TO DATABASE TABLE

    please suggest me the simplest code of image insertion in the database table.

    this is an example:>
    public static void AddEmployee(
    string lastName,
    string firstName,
    string title,
    DateTime hireDate,
    int reportsTo,
    string photoFilePath,
    string connectionString)
    byte[] photo = GetPhoto(photoFilePath);
    using (SqlConnection connection = new SqlConnection(
    connectionString))
    SqlCommand command = new SqlCommand(
    "INSERT INTO Employees (LastName, FirstName, " +
    "Title, HireDate, ReportsTo, Photo) " +
    "Values(@LastName, @FirstName, @Title, " +
    "@HireDate, @ReportsTo, @Photo)", connection);
    command.Parameters.Add("@LastName",
    SqlDbType.NVarChar, 20).Value = lastName;
    command.Parameters.Add("@FirstName",
    SqlDbType.NVarChar, 10).Value = firstName;
    command.Parameters.Add("@Title",
    SqlDbType.NVarChar, 30).Value = title;
    command.Parameters.Add("@HireDate",
    SqlDbType.DateTime).Value = hireDate;
    command.Parameters.Add("@ReportsTo",
    SqlDbType.Int).Value = reportsTo;
    command.Parameters.Add("@Photo",
    SqlDbType.Image, photo.Length).Value = photo;
    connection.Open();
    command.ExecuteNonQuery();
    public static byte[] GetPhoto(string filePath)
    FileStream stream = new FileStream(
    filePath, FileMode.Open, FileAccess.Read);
    BinaryReader reader = new BinaryReader(stream);
    byte[] photo = reader.ReadBytes((int)stream.Length);
    reader.Close();
    stream.Close();
    return photo;
    Mark as answer or vote as helpful if you find it useful | Ammar Zaied [MCP]

  • Insert Image in database from Java Prog, but some excp. occured

    I want to insert the content of an Image file into my database, but I am getting the below exception.
    I am reading the file and taking the content into a string. The string displays perfectly (if I print the string using system.out.println statement) but while inserting into database it gives problem.
    Following is my code::
    import java.io.*;
    import java.sql.*;
    public class ImageInsert
    public static void main(String args[])
    try
    DataInputStream dis = new DataInputStream(new FileInputStream("reshmi.gif"));
    String str="" , ImageContent="";
    while((str = dis.readLine()) != null )
    ImageContent = ImageContent + str;
         //System.out.println("Content :"+ str);
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:somedata" , "sa" , "");
    Statement st = con.createStatement();
    String as = "INSERT INTO TESTIMAGE (ImageFile) VALUES(\"" + ImageContent + "\")" ;
    int q = st.executeUpdate(as);
    System.out.println("The data Inserted:"+q);
         }catch(Exception er) {er.printStackTrace();}
    // end of code
    Where as if I insert it manually in my SQL Server executing the insert statement it inserts the image perfectly:
    Following Exceptions I am receivng :
    *********** BELOW IS THE EXCEPTION********
    java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation m
    ark before the character string 'GIF89a��'.
    at sun.jdbc.odbc.JdbcOdbc.createSQLException(Compiled Code)
    at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:4246)
    at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:1172)
    at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:206)
    at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(JdbcOdbcStatement.java:163)

    It looks like imageContent contains a quote character, making your statement invalid. Something like
    Insert into .... value("<some chars>..."...<some chars>")
    Using single quotes will not resolve this problem since imageContent could also contains single quote chars.
    Try using BLOBs instead strings. I don't know if SQLServer supports BLOBs but Oracle does.
    JCG

  • Image in database

    Insert into table
    values(?,?)
    In one of the code for inserting image into database ,for values " ? " has been put.What am I suppose to put therre .while storing an image into oracle 9i database it gives me error as Invalid hex number.
    I am using JSP as my front end

    catch(Exception e)
    System.out.println(e);
    }Exceptions have the wonderful printStackTrace() method which show you which line and which sourcefile actually caused the exception.
    byte b[]=new byte[is.available()];
    is.read(b);This looks dangerous. available() is not guaranteed to return the total size of the image.

  • Inserting images is taking too much time(PT)

    Hi,
    when i'm inserting images into database 10g it is taking much time than usual ..and other dml operations are normal..how can i make it fast .thanks in advance
    Edited by: startup on Oct 10, 2011 4:53 PM
    Edited by: startup on Oct 10, 2011 5:18 PM

    startup wrote:
    Hi,
    when i'm inserting images into database it is taking much time than usual ..and other dml operations are normal..how can i make it fast .Maybe using "parallel" hints, Please provide your DB version and OS Name

  • How to Insert Hastables Into Database Through JDBC

    hi all,
    I have place the Data from the Hashtables Into the Database.I can place it by Iterating through the Hastables.I would Like to Place the Entire Hashtable Itself Into the Database.
    Can Any one tell me how?
    bye.

    Hi,
    Can anyone help me out how to insert image into
    database using struts...with dao n dto classes?If it matters whether or not you are using struts then you might have something wrong.
    Make sure you separate the database logic out.
    I know these types of questions are asked frequently, you might want to search the forum for additional examples.
    Here is a good one:
    http://forum.java.sun.com/thread.jspa?threadID=620455&messageID=3495899

  • Inserting image in to mysql

    hi
    i am developing the web application in which i want to put record of
    in which there is the image
    and i dont know hove to insrt image in database using jsp or servlet
    if anyone have anser plz .

    Following your blob instruction, I also haveproblems inserting
    images to MySQL. Those blobs have good examples butthey
    assume PHP. What about JSP? Anyone? PS. Sorry forposting throug
    someone else's threadi usually use only byte array to store data like
    image (in jpeg, the file size is not so big).The database is set up. PHP does the job for me. What about JSP? That is the question. Not how big an array you may use :-)

  • JSP and Images with database

    Ok, I have looked around on posts on this forum but still haven't come across an answer. I am trying to create a simple jsp page that contains some thumbnail images. The image locations are stored in a mysql database (e.g. http://www.somewhere.com/images/image1.jpg"). Assuming that I didn't know how many images were stored in the mysql table, how can I set up a jsp page that will automatically retreive all the image locations from the database and put the appropriate tags in the jsp to display all the images in an html table? In other words, I am trying to avoid writing in the jsp page a bunch of <tr><td><img src=.....></td></tr> statements. Do I need to do this with a tag library? You help is much appreciated! Let me know if I need to be more clear.
    Keith

    <%@page import="java.sql.*" %>
    <table boder="1">
    <%
    Statement statement;
    Connection conn;
    String url = "jdbc:mysql://localhost/dbName";
    String user = "username";
    String pass = "password";
    try {
        class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(url, user, pass);
        statement = conn.createStatement();
    String query = "SELECT images FROM database";
    ResultSet results = statement.executeQuery(query);
    while(results.next()) {
    %>
        <tr>
            <td><img src="<%= results.getString("images") %>"></td>
        </tr>
    <% } %>
    </table>The while loop will loop through your result set and print the table row for each image it finds in the query.
    Hope this helps,
    Jon

  • This is my Jsp code for image upload in database:

    This is my Jsp code for image upload in database:
    -----------Upload.jsp----------------
    <html>
    <head>
    </head>
    <body bgproperties="fixed" bgcolor="#CCFFFF">
    <form method="POST" action="UploadPicture.jsp" enctype="multiform/form-data">
    <%! int update=0; %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.text.*" %>
    <%@ page import="java.sql.Date" %>
    <%@ page import="java.io.*"%>
    <%@ page language = "java" %>
    <%
    try
    String ct="3";
    String path;
    File image=new File(request.getParameter("upload"));
    path=request.getParameter("upload");
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:itPlusElectronics","","");
    PreparedStatement pstmt=con.prepareStatement("insert into graphics values(?,?,?)");
    pstmt.setString(2,path);
    pstmt.setString(3,ct);
    InputStream is=new FileInputStream(path);
    pstmt.setBinaryStream(1, is, (int)(image.length()));
    int s=pstmt.executeUpdate();
    if(s>0)
    out.println("Uploaded");
    else
    %>
    unsucessfull
    <%}
    is.close();
    pstmt.close();
    catch(Exception e)
    }%>
    </p>
    <p><br>
    <img src="UploadedPicture.jsp">image</img>
    <p></p>
    </form>
    </body>
    </html>
    My database name is itPlusElectronics and the table name is "graphics".
    I have seen as a result of the above code that the image is stored in database as "Long binary data". and database table is look like as follows-------
    picture path id
    Long binary data D:\AMRIT\1-1-Picture.jpg 3
    To retrive and display i use this JSP code as--
    ------------------------UploadedPicture.jsp------------------------------
    <html>
    <head>
    </head>
    <body bgproperties="fixed" bgcolor="#CCFFFF">
    <%! int update=0; %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.text.*" %>
    <%@ page import="java.io.*"%>
    <%@ page language = "java" %>
    <%@page import="javax.servlet.ServletOutputStream"%>
    <%
    try
    String path;
    path=request.getParameter("upload1");
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:itPlusElectronics","","");
    PreparedStatement pst = con.prepareStatement("SELECT * FROM graphics WHERE id ='3'");
    // pst.setString(3, id);
    ResultSet rs = pst.executeQuery();
    path=rs.getString("path");
    if(rs.next()) {
    byte[] bytearray = new byte[4096];
    int size=0;
    InputStream sImage;
    sImage = rs.getBinaryStream(1);
    response.reset();
    response.setContentType("image/jpeg");
    response.addHeader("Content-Disposition","filename=path");
    while((size=sImage.read(bytearray))!= -1 )
    response.getOutputStream().write(bytearray,0,size) ;
    response.flushBuffer();
    sImage.close();
    rs.close();
    catch(Exception e)
    %>
    </body>
    </html>
    Now after browsing a jpg image file from client side and pressing submit button ;
    I am unable display the image in the Upload.jsp file.Though I use
    <img src="UploadedPicture.jsp">image</img> HTML code in Upload.jsp
    file .
    Now I am unable to find out the mistakes which is needed for displaying the picture in the Upload.jsp page..
    If any one can help with the proper jsp code to retrive and display the image ,please please help me !!!!!!!!!!!!!!!!!!!!!!!!!!

    dketcham wrote:
    cotton.m wrote:
    >
    2) I'm looking at how you called stuff, and you're trying to call the jsp file as an image? That jsp isn't the source of the image, just a page linking to an image. I think if you really want to do things that way you're going to need to just include that jsp within the jsp you're calling it from (or you can do it the easy way, and if you have the information to get the path of the image you want, you could simply call the image from the first jsp you posted)This is incorrect.
    There are two JSPs. The second when called will (if it worked) return the source of an image as stored in the database.even when called with <img src=xx.jsp>??
    Yes.
    If any of what I say next seems obvious or otherwise negative I apologize, just trying to explain and I don't know what you know vs what you don't.
    The link in the src is just a URL not a filetype. So just because it ends with JSP does not mean it has to return HTML. The content type is determined by the browser using the Content-Type header returned by the server in the HTTP response. In this case the header is set to be a jpeg so that's what the browser will attempt to interpret the content part of the response as.
    So in fact one is not limited to just HTML or images but whatever content type you would like to return (that the browser can understand anyway). This could be HTML or it could be an image of some type or it could be a PDF or it could be an Excel spreadsheet. All you have to do in the JSP is set the header appropriately and then send content that is actually in that format.
    This does not just apply to JSP by the way but all other web programming languages. You can do similar things to produce the same results in PHP, Perl, ASP etc.
    The only JSP/Servlet complication is whether or not doing this in a JSP is a "good" idea but I am not an expert enough at that to make a definitive statement. Mostly though JDBC in a JSP is a no-no.

  • Hashtable for multi part form to insert image and details to database:)

    Hey guys do you have any samples on using hashtable in multipart form to insert image as well as details into database?:)
    Oh it is because my form is using multipart from that enbales me to upload/Insert image into my database.
    Howerver, I also need to insert other details into my database such as productid, ProdName, unitprice.....
    Hence, My tutor suggested using hashtable.
    However, I do not understnd.
    Do you guys have any samples regarding on this?
    Thanks
    :D

    Cathy_Latte wrote:
    However, I do not understnd. More specifically: you do not understand how to use Maps? If so, just go through a book/tutorial on that subject. In fact you should have consulted your tutor or classmates for more information and you're here at a JSP/JSTL forum at the wrong place (you have a problem with Java in general, not with JSP), but OK, here's a link: [http://google.com/search?q=hashmap+tutorial+site%3Asun.com].

  • Inserting image in to database !!

    Hi All,
    I have to insert image in to the database. My image is there in swing object Image. Is there any way to insert that image in to the database.
    Any body having knowledge on this, Please help.
    Thanks in advance.
    Regards,
    Roja.

    Hi
    Take a look to this code I found surfing, it creates an image from url then resize it and return it as byte array that you can use to set a blob in the database:
    public static byte [] resizeImage(URL url,int widthConstraint,int heightConstraint) throws ImageFormatException, IOException
         ImageIcon imageIcon = new ImageIcon(url);
         Image img = imageIcon.getImage();
         int imgWidth = imageIcon.getIconWidth();
         int imgHeight = imageIcon.getIconHeight();
         ImageIcon adjustedImg=null;
         if ( imgWidth>0 && imgHeight>0)//imgWidth > widthConstraint | imgHeight >  heightConstraint )
         if ( imgWidth > imgHeight )
           // Create a resizing ratio.
           double ratio = (double) imgWidth / (double)
            widthConstraint;
           int newHeight = (int) ( (double) imgHeight / ratio );
           // use Image.getScaledInstance( w, h,
           // constant), where constant is a constant
           // pulled from the Image class indicating how
           // process the image; smooth image, fast
           // processing, etc.
           adjustedImg = new ImageIcon(
            imageIcon.getImage().getScaledInstance(
              widthConstraint, newHeight,
              Image.SCALE_SMOOTH )
         else
           // Create a resizing ratio.
           double ratio = (double) imgHeight / (double)
            heightConstraint;
           int newWidth = (int) ( (double) imgWidth / ratio );
           adjustedImg = new ImageIcon(
           imageIcon.getImage().getScaledInstance( newWidth,
              heightConstraint, Image.SCALE_SMOOTH )
         int resizeWidth = adjustedImg.getIconWidth();
         int resizeHeight = adjustedImg.getIconHeight();
         Panel p = new Panel();
         BufferedImage bi = new BufferedImage(resizeWidth, resizeHeight,
         BufferedImage.TYPE_INT_RGB);
         Graphics2D big = bi.createGraphics();
         big.drawImage(adjustedImg.getImage(), 0, 0, p);
         ByteArrayOutputStream os = new ByteArrayOutputStream();
         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
         encoder.encode(bi);
         byte[] byteArray = os.toByteArray();
         return byteArray;
      else
      return new byte[0];
       }hope this helps.

  • Insert Image file from java to ms access database

    Are there any ways to insert image file or any files into microsoft access database and retrieve the file from the database. Guild will be helpful.Thank you.
    regards
    Singaravelan

    The right answer? Don't do it. You should not be putting images in any database.
    Better to write the image to the server's file system and add the path/link to the database instead.
    %

  • Inserting date from a jsp into sql server 2005 database

    Dear Friends.,
    i have a jsp page, in that there is a form with various user input fields. in that one field is date field. i tried to insert the date field into the sql server 2005 database. but it is not getting inserted into the database.
    when i tried by inserting one field to database, it is getting inserted. for all the fields its works fine, except the date field.
    i need hint or code to insert the date get from the jsp page to database.
    i am using a servlet to do all database related things. i.e making connections, executing prepared statement queries
    thanks
    sekar.

    The variable needs to be outside of the string to be recognized as a variable. You need to remove the variable from the string, then concatinate it onto the string (and concatinate any remaining string parts - the closing paren). For example:
    stmt.executeUpdate("INSERT INTO table VALUES ('test', " + companyID + ")");
    Hope that's clear enough and helps. Good luck on your thesis!
    jim

Maybe you are looking for