Saving image in MySQL database

Best groupmember,
I want to save my images in a MySQL database. After storing that in the database I want to be able to present it using a servlet. Something like this (show image with id=4 from the database):
<img src="/servlet/image?id=4">
Would be happy to be guided to example code or tutorials about how to store images in a MySQL database using Java.
-- Best of Times
Peter Lauri

Ok for storing images you'll have to use the type BLOB (=Binary Large Object) for the rest i would suggest that you take a look at the jdbc-documentation....
this might help... :p
http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSet.html#getBlob(int)

Similar Messages

  • Data type for Saving Image in SQL database

    Hi,
        Which is the best way for saving images in the database? Filestream or Varbinary(max)?. Will the Varbinary max comsume much space or it will only take the actual size of the data?

    I've used FILETABLE for storing images in SQL 2012
    You can configure it to have transact and non transact access if you want
    see
    http://visakhm.blogspot.in/2012/07/working-with-filetables-in-sql-2012.html
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Upload image into mysql database residing on  remote server is not working?

    hello to all,
    i need ur help,we hav online site .
    i have to upload image(which can b from any pc) into mysql database residing on remote server of which we (don't hav actual path of that server).
    the solution i'm using is working correctly on local bt when transfer it to server it shows
    java.io.FileNotFoundException: (No such file or directory)
    i have used multipartRequest to access parameter of file type input.
    all variables and related packages r imported properly.no prblm in that.
    code is here....................................
    try {
    MultipartRequest multi = new MultipartRequest(request, ".", 500000 * 1024);
    File f = multi.getFile("uploadfile");
    out.println(f.getName());
    filename = f.getName();
    String type = multi.getContentType(f.getName());
    fis=new FileInputStream(filename);
    byte b[]=new byte[fis.available()];
    fis.read(b);
    fis.close();
    Blob blob=new SerialBlob(b);
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql://10.1.52.206:3306/test?user=root&password=delhi");
    String query="insert into uploads (FILENAME,BINARYFILE,) values (?,?)";
    pstmt=con.prepareStatement(query);
    pstmt.setString(1,filename);
    pstmt.setBlob(2,blob);
    int i=pstmt.executeUpdate();
    if(i>0)
    out.println("Image Stored in the Database");
    else
    out.println("Failed");
    } catch (Exception ex) {
    out.print("*******************"+ex);
    ex.printStackTrace();
    please suggest me the way to upload image to remote server** not on local server.
    its urgent.
    Edited by: JavaDevS on Jul 28, 2008 11:41 AM

    i need ur help,we hav online site .Please don't use these juvenile abbreviations. It's impolite when you're asking for assistance not to make the effort to spell out all of the words. Moreover in a forum with an international readership the use of standard English will reduce the possibility of confusion.
    I presume that your file upload is being placed in a different directory from that which you were expecting. I would suggest logging all paths (specifically filename) to see if this is an unexpected value.
    Please explain further what you mean by "local" - is this a stand-alone application, or merely running a copy of the server on your local machine and doing the transfer (via the browser) to that? Are there any other differences such as the browser used?

  • How to upload images to MySql database.

    Hey guys so i created a insert form in dreamweaver to add to a database, its workin fine but i want to add another field to browse for and add a small image of the item. I created my insert form with a wizard and I'm not sure how to add an image uploader to it. I have a blob field in my database called "image" I'm just not sure how to add to it from my form.  Here is the code for my insert page so far:
    <?php require_once('../Connections/cbdb.php'); ?>
    <?php require_once('Zend/Date.php'); ?>
    <?php
    if (!isset($_SESSION)) {
      session_start();
    $MM_authorizedUsers = "";
    $MM_donotCheckaccess = "true";
    // *** Restrict Access To Page: Grant or deny access to this page
    function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
      // For security, start by assuming the visitor is NOT authorized.
      $isValid = False;
      // When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
      // Therefore, we know that a user is NOT logged in if that Session variable is blank.
      if (!empty($UserName)) {
        // Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
        // Parse the strings into arrays.
        $arrUsers = Explode(",", $strUsers);
        $arrGroups = Explode(",", $strGroups);
        if (in_array($UserName, $arrUsers)) {
          $isValid = true;
        // Or, you may restrict access to only certain users based on their username.
        if (in_array($UserGroup, $arrGroups)) {
          $isValid = true;
        if (($strUsers == "") && true) {
          $isValid = true;
      return $isValid;
    $MM_restrictGoTo = "login.php";
    if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {  
      $MM_qsChar = "?";
      $MM_referrer = $_SERVER['PHP_SELF'];
      if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
      if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
      $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
      $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
      header("Location: ". $MM_restrictGoTo);
      exit;
    ?>
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
      if (PHP_VERSION < 6) {
        $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
      $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      switch ($theType) {
        case "text":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;   
        case "long":
        case "int":
          $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case "double":
          $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
          break;
        case "date":
          if ($theValue == "")
        $theValue = "NULL";
       else
        $zendDate = new Zend_Date($theValue, "d/M/yyyy");
        $theValue = "'" . $zendDate->toString("yyyy-MM-dd") . "'";
          break;
        case "defined":
          $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
          break;
      return $theValue;
    // *** Redirect if username exists
    $MM_flag="MM_insert";
    if (isset($_POST[$MM_flag])) {
      $MM_dupKeyRedirect="stock_already_exist.php";
      $loginUsername = $_POST['registration'];
      $LoginRS__query = sprintf("SELECT registration FROM stock WHERE registration=%s", GetSQLValueString($loginUsername, "text"));
      mysql_select_db($database_cbdb, $cbdb);
      $LoginRS=mysql_query($LoginRS__query, $cbdb) or die(mysql_error());
      $loginFoundUser = mysql_num_rows($LoginRS);
      //if there is a row in the database, the username was found - can not add the requested username
      if($loginFoundUser){
        $MM_qsChar = "?";
        //append the username to the redirect page
        if (substr_count($MM_dupKeyRedirect,"?") >=1) $MM_qsChar = "&";
        $MM_dupKeyRedirect = $MM_dupKeyRedirect . $MM_qsChar ."requsername=".$loginUsername;
        header ("Location: $MM_dupKeyRedirect");
        exit;
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
      $insertSQL = sprintf("INSERT INTO stock (make, model, `year`, cc, fuel, doors, body, `date`, registration, keywords) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                           GetSQLValueString($_POST['make'], "text"),
                           GetSQLValueString($_POST['model'], "text"),
                           GetSQLValueString($_POST['year'], "text"),
                           GetSQLValueString($_POST['cc'], "text"),
                           GetSQLValueString($_POST['fuel'], "text"),
                           GetSQLValueString($_POST['doors'], "text"),
                           GetSQLValueString($_POST['body'], "text"),
                           GetSQLValueString($_POST['date'], "date"),
                           GetSQLValueString($_POST['registration'], "text"),
                           GetSQLValueString($_POST['keywords'], "text"));
      mysql_select_db($database_cbdb, $cbdb);
      $Result1 = mysql_query($insertSQL, $cbdb) or die(mysql_error());
      $insertGoTo = "stock_added.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      header(sprintf("Location: %s", $insertGoTo));
    mysql_select_db($database_cbdb, $cbdb);
    $query_rsStock = "SELECT * FROM stock ORDER BY stockId ASC";
    $rsStock = mysql_query($query_rsStock, $cbdb) or die(mysql_error());
    $row_rsStock = mysql_fetch_assoc($rsStock);
    $totalRows_rsStock = mysql_num_rows($rsStock);
    ?>

    supersham101 wrote:
    Hey guys so i created a insert form in dreamweaver to add to a database, its workin fine but i want to add another field to browse for and add a small image of the item. I created my insert form with a wizard and I'm not sure how to add an image uploader to it. I have a blob field in my database called "image" I'm just not sure how to add to it from my form.
    Storing images in a database is generally not a good idea. Apart from bloating your database and increasing the risk of table fragmentation when images are updated or deleted, you cannot display an image directly from a database. However, if you want to do it, you will find instructions here: http://cookbooks.adobe.com/post_Upload_images_to_a_MySQL_database__PHP_-16609.html.
    The more common (and efficient) approach is to use the database to store details of the image, such as filename and caption. Then upload the image to your website's file system.
    I give step-by-step instructions how to do this in my book, "Adobe Dreamweaver CS5 with PHP: Training from the Source", but if you have reasonable skill at using PHP, you can learn how to handle file uploads from the PHP Manual at http://docs.php.net/manual/en/features.file-upload.php.

  • Saving images on my database and calling the open file dialog

    i want to be able to save image in my database or alternatively save them on a file system. meanwhile i want to allow them choose the name of the image in the folder by using the win_api_dialog.open_file. My platform is win2000. do i need to add any other thing to this like a particular library or just anything. please i need this help urgently.database os is unix ware.

    Hello,
    You can do this without using library. Suppose you have a table with BLOB data type column and one form which has image box to display and store image boxes.
    Now by using READ_IMAGE_FILE read picture file. To write picture to file use WRITE_IMAGE_FILE. and
    if you want to give users open file dialogue box then use GET_FILE_NAME builtin.
    All the best.
    Adinath Kamode

  • Saving image in ms sql database.

    Hi all, i have a problem saving image in the database.i used
    request.getParameter("imagename"), to get the content of the textfield in the html file but the problem is that it omits the filepath and gives me just the image name and that gives me an error.. Pls help me

    Your actual problem is less or more web browser related. The right way is that the browser should only send the filename, but a certain widely used browser developed by a team in Redmond would send the full file path as it is at the client side, which is completely wrong.
    The bigger picture what you're trying to achieve, uploading a file from the client to the server, shouldn't be done that way, simply because this isn't going to work at all if the client runs at a completely different machine on the other side of the network than where the server runs. You need to send the actual file contents to the server. Just set the form's enctype to multipart/form-data and parse the body of the request to get the actual file contents. To ease the work I recommend you to use Apache Commons FileUpload API for parsing the multipart/form-data request. Go to their homepage and check out the 'User guide' and 'Frequently Asked Questions' how to use it and for some tricks.

  • Images from MySQL

    Hi;
    I'm comfortable sending data to and from python scripts and as3, but what about blobs? I have images stored in MySQL. How should I get these into as3?
    Thanks,
    Terry

    Chrisjuk wrote:
    > I would be greatly appreciative if someone could
    > do me a quick guide to saving images to MYSQL and then
    displaying them in
    > Dreamweaver.
    Here's an extremely quick guide to saving images in MySQL (or
    any other
    database for that matter): DON'T DO IT.
    Databases are for storing data, not images. Store the images
    in the
    normal file system, and use the database to store details of
    where the
    image is located.
    Yes, you can store images in a database, but it leads to
    table bloat,
    and fragmented tables. It also involves quite a lot of
    scripting, which
    is not automatically generated by Dreamweaver.
    David Powers, Adobe Community Expert
    Author, "The Essential Guide to Dreamweaver CS3" (friends of
    ED)
    Author, "PHP Solutions" (friends of ED)
    http://foundationphp.com/

  • Saving a document in Database

    Hi all,
    I am opening file from Mysql server using JSP and Tomcat. It opens in the associated program not in the browser. when it opens say, a word file is opened from database in MS Word. When try to change anything on that file, if i press save then it saves but i realised that it is saving in my computers
    C:/Documents/Local Settings/Temporary Internet Files/Content.IE5/UA40NN" folder
    Not saving in the MySQL database from where it was opened.
    This means that if anyone wants to change any document then they need to download that document, change it and then upload the updated version to the database.
    But this is a time cosuming process for the organisation.
    So can anyone please help me how can i save document in database by opening it and then making necessary changes in it.
    Thanks

    This means that if anyone wants to change any document then they need to >download that document, change it and then upload the updated version to the >database.Correct!!
    So can anyone please help me how can i save document in database by >opening it and then making necessary changes in it.You cannot, you will have to change the local copy, then upload it as you originally thought.
    An alternative would be to save the files on a networked drive which users can access directly. You could then store the file name and path in the database. Then when users opened the file, it would be the central copy.
    You could add code to delete documents etc. through your web interface.

  • Question on retrieve image from mysql

    i want to retrieve image from mysql database and display on GUI
    can anyone tell me how to do
    Thank you

    You can use the JDBC API for Java Database Connectivity. With this you can obtain data from the database using Java. There is an excellent tutorial here at Sun.com: http://www.google.com/search?q=jdbc+tutorial+site:sun.com You can get the MySQL JDBC driver at their own site: http://www.google.com/search?q=download+jdbc+driver+site:mysql.com Get the most recent version which suits your environment. There is also good documentation available over there.
    For displaying in the UI, the approach differs per UI. As you didn't mention which UI you are using, I can't help you further in detail.

  • How to insert an image into mysql

    welcome to all,
    can any one tell how to insert an image into mysql database(BLOB). it is urgent.
    regards

    welcome to all,
    can any one tell how to insert an image into mysql database(BLOB). it is urgent.
    regards

  • Problem in saving the image into SQL database..

    Hello,
    In my application I have to save image file (say jpg) into the database and retrieve back and display it on the applet. I am through with grabbing the pixels of the image & sending the pixel array to the servlet but I am struck in how to store the image into the database and retrieve the same.
    Can anybody please help me in this regard... its really urgent...
    Thanks in advance
    Swarna

    Hello.
    I've been researching this problem (saving images in a MySQL database) in order to accomplish a task I was assigned to. Finally I was able to do it. I'd be glad if it will be of any use.
    First of all: the original question was related to an applet. So, the post from rkippen should be read. It says almost everything, leaving the code job for us. Since I managed to write some code, I'll put it here, but I'm not dealing with the byte transferring issue.
    To obtain a byte array from a file I'd open the file with FileInputStream and use a loop to read bytes from it and save them into a ByteArrayOutputStream object. The ByteArrayOutputStream class has a method named �toByteArray()� which returns an array of bytes (byte [] b = baos.toByteArray()) that can be transferred in a socket connection, as said by rkippen.
    My problem was to save an image captured by a web camera. I had an Image object, which I converted into a byte array and saved into the database. Eventually I had to read the image and show it to the user.
    The table in the MySQL database could be:
    CREATE TABLE  test (
      id int(11) NOT NULL auto_increment,
      img blob NOT NULL,
      PRIMARY KEY  (id)
    )I had problems trying to use the �setBlob� and �getBlob� methods in the Statement object, so I used the �setBytes� and �getBytes� methods . In the end, I liked these methods most because they where more suitable to my application.
    The database operations are:
        public int insertImage(Image image) throws SQLException {
            int id = -1;
            String sql = "insert into test (img) values (?)\n";
            PreparedStatement ps = this.getStatement(sql);  // this method is trivial
            byte [] bytes = this.getBytes(imagem); // * see below
            ps.setBytes(1, bytes);
            ps.executeUpdate();
            id = ps.getGeneratedKeys().getInt(0); //Actually I couldn't make this line work yet.
            return id;
        public Image selectImage(int id) throws SQLException {
            Image img = null;
            String sql = "select img from test where id = ?\n";
            PreparedStatement ps = getStatement(sql);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                byte [] bytes = rs.getBytes(1);
                img = this.getImage(bytes); // * see below
            return img;
        }* If the bytes are read directly from a file, I think it is not necessary to convert it into an Image. Just send the bytes to the database method would work. On the other hand, if the image read form the DB will be written directly into files, the bytes obtained from rs.getBytes(1) would be enough.
    The image operations are:
        public byte [] getBytes(Image image) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ImageIO.write(this.getBufferedImage(image), "JPEG", baos);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            return baos.toByteArray();
        public Image getImage(byte [] bytes)  {
            Image image = null;
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            try {
                image = ImageIO.read(bais);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            return image;
        public BufferedImage getBufferedImage(Image image) {
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = bi.createGraphics();
            g2d.drawImage(image, 0, 0, null);
            return bi;
        }That's it. I hope it is useful.

  • Saving images in a mysql db?

    Hi you all,
    I have a question.
    I'm working on a school project. And I was wondering if it is possible to save an image to a MySQL db with java.
    I would like to save an specified image to the database, but I'm also wondering is I could display the image from the database again (I prefere that there is no temp file created).
    (I have done this before with PHP)
    Does anyone has ideas or sample codes for me?
    Please hurry, I have only short time to finish the project.
    With Kind Regards,
    Franck Nijhof
    (ps sorry my bad english)

    I know that file in system is better. But in out project we must be saving a binary file in the database. A image is not that big and can be used usefull.
    So I like to do an image instead of an big program.
    (BTW I need it anyway, we need to build the program multiuser with network, this mean one is loading the image and everybody need to get it if they want to)
    Hopefully some can help!
    With kind regards,
    Franck Nijhof

  • Save an Image in a MySQL database

    I am trying to save an image in a MySQL database. This is what I have done so far; I have created a table with one of the variables called
    photo  blob, this is what you use to save an image right?
    When I write the image to the database after getting connected to it is where I am stuck, so far I can save Ints, Strings and Enum s values but I do not know how to convert my image into a Blob and save the blob. I have been doing some light reading and I am guessing I have to convert the image into a Stream of some sort. What type of stream I do not know. This is the java command I have to save the Blob but do not know what to use as the variable for the Blob.
    prst.setBlob(5,  "??????");As you can tell by the ????? marks, I do not know how to convert my image into the proper data type(whatever the data type is?) to save the contents into the database.
    If somebody has the exact copy of the all the java coded steps that is needed to save an image as a Blob into a prepared database, that would be extremelu helpful to me.
    Thank-you.

    The answer has to be quite simple. If you do not have
    the answer please do not reply.Unfortunately it's not simple. This is one of my betes noire about the java libaries. The Blob stuff has gaping holes in it. There's no method, anywhere, to create a new Blob or Clob (also the design of the Blob and Clob interfaces tends to miss the point).
    The ways arround this, there being no legitimate approach, vary with the database provider.
    If the program an the server are running on the same machine (or files can be shared through NFS or the like) you can try the "LOAD_FILE" function.
    With some databases I believe setBinaryStream instead of setBlob works, but I'm not sure the mySql driver is that smart.

  • Saving images in database

    Hi all,
    Pls what is the best way for putting the employees photos into
    the personal application?
    is it ok to save the Pics to the table or to the database.
    Pls advise me.
    Best Regards.

    Hi ,
    It is better to save the images in the Database in the
    Blob column in a Emp Table.

  • Saving images into database

    Hi All,
    I have a table with 3 BLOB columns to store images and a NUMBER type column to store the image id_no. I am using database 10g and Forms 6i
    My problem is I recently updated the database from 8i to 10g, and since then I am unable to update or insert the new images in these BLOB columns. When I update the existing image or insert new image record through forms, It does save the changes in existing or new record. But It does not show these images while query the record. and also does not give any error while executing the query in forms.
    But while trying to retrive the image from updated records or new record in reports, It throughs the error that image is format is unreadable or currupt.
    There wasn't any problem in 8i, i could update the record as many times I wanted or create as many records as needed.
    Is anybody have any clue about this problem! Any help in this regard will be highly appriciated.
    Thanking you and Best Regards.

    You should not save an image to database, since it'll make database slow, and difficult to write a web page to load image.
    Save an image to specific location, and save image location to database.
    Then, use <img> tag to call an image in web page.

Maybe you are looking for

  • How to send an attached file containing with non-ascii code ?

    Hi, I want to send a attaced text file containing with non-ascii code(Traditional Chinese). Is there any way to solve the encoding problem? Currently, it transfer into non-meaningful code in receiving side. Thanks for the help in advance.

  • Unicode Conversion in a system landsacpe

    Hello, we are planning a unicode conversion of our productive system. Our productive system is the source system of several systems like BI, mobile engine, webshop and so on. About the problems of unicode conversion within the productive system I hav

  • Folder Action works, but only once

    Attached a Folder Action to a folder in my Home directory, to upon dropping folders/files to that folder will change the Folder Views to 128 Icon size (and subfolders) - works once, then next time I drop a folder into that folder doesn't do anything.

  • I need Help for that program

    i do aprogram for sample calculator by Java there it , i Hope if u have any sugesst say to me Or if u have a program for that. import java.applet.*; import java.awt.*; import java.awt.event.*; public class Z extends Applet implements ActionListener {

  • Wild cards in custom views

    Is there a way to use wild cards in the sql in custom views in Discoverer? We can allow a parameter in the actual report but one of the tables we're using has term effective dates instead of actual term dates so we need to pull info from the term eff