0

<form:form id="companyForm" enctype="multipart/form-data" method="POST"
  action="/DTR/secured/admin/company/save" commandName = "command">

So, I was asked to save an image file to a database, but since DB don't have image file data type, I have to use multipart. Can someone explain to me how does it work? How am I gonna do it? And how can I retrieve the data and then convert it again to an image? I cant find an article that can help me, and if you have, feel free to comment it. Thanks.

The Impaler
  • 45,731
  • 9
  • 39
  • 76
Adzz
  • 77
  • 1
  • 6
  • OK little boy the the muscle shirt... This comment is obsolete, chatty, or otherwise unnecessary -> flagged. Maybe this comment even violates the "[be nice](https://stackoverflow.com/help/be-nice)" policy. -> flagged a second time? This is really not necessary. But thanks for your intervention:) –  Jun 18 '18 at 06:17

2 Answers2

3

You probably should read more about such type as BLOB. Your question combines two themes:

  1. How to upload media using JSP
  2. How to store image in DB

Both question were already several times answered on this site but below you can find some instructions in one place. Because you didn't provide information about which DB do you use I will explain how to make this working in oracle.

1.First you need to create new user in oracle. Below you can find sql script for creation of TEST user.

CREATE USER TEST IDENTIFIED BY TEST DEFAULT TABLESPACE USERS TEMPORARY TABLESPACE TEMP PROFILE DEFAULT ACCOUNT UNLOCK;
GRANT CONNECT, RESOURCE, IMP_FULL_DATABASE, CREATE VIEW, UNLIMITED TABLESPACE, CREATE JOB TO TEST;

2.Then you need to create a table with column image which will store your image

create table test.image_storage (image blob);

3.Create your JSP and create form for your image upload:

<form action="upload" method="post" enctype="multipart/form-data">
        <input type="text" name="description" />
        <input type="file" name="file" />
        <input type="submit" />
</form>

4.Register your servlet:

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    public static final String QUERY = "INSERT INTO IMAGE_STORAGE (IMAGE) VALUES (?)";
    public static final String CONNECTION_URL = "jdbc:oracle:thin:@localhost:1522:orcl";
    public static final String USER_NAME = "TEST";
    public static final String USER_PWD = "TEST";
    public static final String FILE_PARAMETER = "file";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part filePart = request.getPart(FILE_PARAMETER);
        InputStream fileContent = filePart.getInputStream();
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("Oracle driver is absent?");
            e.printStackTrace();
        }

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(
                    CONNECTION_URL, USER_NAME, USER_PWD);
            PreparedStatement statement = null;
            try {
                statement = connection.prepareStatement(QUERY);
                statement.setBlob(1, fileContent);
                statement.execute();
            } catch (SQLException e) {
                System.out.println("State cannot be executed!");
                e.printStackTrace();
                return;
            } finally {
                statement.close();
            }
        } catch (SQLException e) {
            System.out.println("Connection Failed!");
            e.printStackTrace();
            return;
        } finally {
            try {
                connection.close();
            } catch (SQLException e) {
                System.out.println("Connection cannot be closed?");
                e.printStackTrace();
            }
        }
    }
}

Once you will upload an image you will see a new entry in your DB: enter image description here

Hope this will help you to understand this topic.

0

Please be aware that I posted this after I browse the web for answers and I didnt get what I need exactly.

@Transient
public CommonsMultipartFile getFile() {
    return file;
}

I used transient tag for the path that the multipart will be passed. then get the parts from the controller with

@Column(name = "IMAGE")
public byte[] getImage() {
    return image;
}

public void setImage(byte[] image) {
    this.image = image;
}

@Column(name = "CONTENT_TYPE")
public String getContentType() {
    return contentType;
}

public void setContentType(String contentType) {
    this.contentType = contentType;
}
@Transient
public String getIconImage() {
    return "data:" + getContentType() + ";base64,"
            + Base64.encode(getImage());
}

If you want to diplay the image form the database. Just use the normal <img src "${iconImage}"/> and then pass the getIconImage() from your Entity model to the Controller.

Adzz
  • 77
  • 1
  • 6