Chris O'Brien
Chris O'Brien

Reputation: 372

Java EE - Upload image to database?

I'm making a fairly basic site for my mother, and seeing as I did some stuff in Java EE and with EJB during college last semester, I'm going to stick to this.

The only issue I am having is uploading images - I can't seem to find any examples.

I'm using entity classes and parameterised queries. This is the code for writing to the database, which is working fine, I'm just setting the blob image value to null for the moment.

@Override
    public void addClothes(String designer, String cname, String ctype, String desc) {
        Clothes c = new Clothes();
        em.persist(c);
        c.setDesigner(designer);
        c.setCname(cname);
        c.setCtype(ctype);
        c.setDescript(desc);
        c.setImage(null);
    }

I have a servlet that takes a file, I'm just not sure how the file, when passed, should be sorted and what I should write to the database (from what I'm seeing, it's byte[])

A hand in the right direction would be appreciated!

Upvotes: 0

Views: 5224

Answers (4)

Chris O'Brien
Chris O'Brien

Reputation: 372

Got it working ! Somewhat, with this code:

public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        out = response.getWriter();
        final String path = "clothesImages" + File.separator + request.getParameter("designer") + File.separator + request.getParameter("ctype") + File.separator + request.getParameter("cname");
        out.println(path);
        String currentDir = new File(".").getAbsolutePath();
        out.println(currentDir);
        final Part filePart = request.getPart("image");
        final String filename = "image.jpg";
        File file = new File(path);
        if (!file.exists()){
            out.println("Dir Doesn't Exist");
            file.mkdirs();
        }
        OutputStream outstream = null;
        InputStream filestream = null;

        try{
         outstream = new FileOutputStream(new File(path + File.separator + filename));
         filestream = filePart.getInputStream();
         int read = 0;
         final byte[] bytes = new byte[1024];
         while(( read = filestream.read(bytes)) != -1){
             outstream.write(bytes, 0, read);
         }
         out.println("New file " + filename + " created at " + path);
        }catch (FileNotFoundException fne) {
        out.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
        out.println("<br/> ERROR: " + fne.getMessage());
        }finally {
        if (out != null) {
            out.close();
        }
        if (filestream != null) {
            filestream.close();
        }
        if (outstream != null) {
            outstream.close();
        }
    }

    }

The only issue I have is setting the file path. The path is

C:\Users\Chris\AppData\Roaming\NetBeans\7.2.1\config\GF3\domain1\

But I want it to save in

Project-war/web/images

Any ideas?

Upvotes: 0

Paul Vargas
Paul Vargas

Reputation: 42030

Once you have the file on the server, either in memory or in a local or temp file (that depends on the framework or libraries that you're using), you will have a reference of a wrapper type.

If you are using Apache Commons File Upload, you have a FileItem reference. For request all contents of the file as byte array:

byte[] contents = fileItem.get();

If you are using Tomahawk of Trinidad, you have a org.apache.myfaces.trinidad.model.UploadedFile reference. For request all contents of the file as byte array, you can use class IOUtils of the Apache Commons IO:

byte[] contents = IOUtils.toByteArray(uploadedFile.getInputStream());

Of if you have a reference of org.apache.myfaces.custom.fileupload.UploadedFile, is more simple:

byte[] contents = uploadedFile.getBytes();

UPDATE

If you are using Java EE 6, you can use new features of Server 3.0 specification for upload files without extra libraries. See the excellent tutorial of BalusC in The BalusC Code: Uploading files in Servlet 3.0

Upvotes: 1

JamesB
JamesB

Reputation: 7894

In your Clothes class, you can add:

@Lob
private byte[] image;

// Getter/Setter methods

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

To work with hibernatehttp://www.mkyong.com/hibernate/hibernate-save-image-into-database/

To work with JDBC:

To Write image into database BLOB using Jdbc , You need to Convert the File into Inputstream. statement.setBinaryStream(2, (InputStream) inputStream,(int) (image.length())); PreparedStatement statement offer method setBinaryStream() which is used to write binary stream into database BLOB column.

Here is a code snippet to help you:

File image = new File("C:/test.jpg");
inputStream = new FileInputStream(image);

Prepared statement = //define as per your table
// set the file binary stream 
statement.setBinaryStream(2, (InputStream) inputStream,(int) (image.length()));

statement.executeUpdate();

Upvotes: 0

Related Questions