0

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!

Chris O'Brien
  • 372
  • 6
  • 25
  • Duplicate of http://stackoverflow.com/questions/7033676/how-to-upload-an-image-and-save-it-in-database – NullPointerException May 20 '13 at 17:14
  • Your approach is right: Save the image as byte[]. – Matthias Herlitzius May 20 '13 at 17:15
  • Had a look at that question already and it didn't help. I suppose my main queries are can I do something like this clothesBean.addClothes(request.getParameter("designer"), request.getParameter("cname"), request.getParameter("ctype"), request.getParameter("desc"), request.getParamter("image"); This is the way I have it working at the moment. I tried looking at this, but as it's only going to be one image per tuple, and there's not going to be a massive amount of tuples, saving to the db seems to be easier. http://forum.codecall.net/topic/64416-javaservlet-file-upload/ – Chris O'Brien May 20 '13 at 17:46

4 Answers4

1

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

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • I'm using JDBC derby with GlassFish as the application server. All parameters are normally in the request object, so for a string or whatever, I would use request.getParameter("param_name") and then pass that value to the bean. – Chris O'Brien May 20 '13 at 17:54
0

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();
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

In your Clothes class, you can add:

@Lob
private byte[] image;

// Getter/Setter methods
JamesB
  • 7,774
  • 2
  • 22
  • 21
  • My class is derived from the database structure - It already contains that with the relevant setters and getters. @Lob @Column(name = "IMAGE") private byte[] image; – Chris O'Brien May 20 '13 at 17:47
  • I'm still not 100% sure. Can I just use request.getParameter() to get the file and write it straight in as is? Do I have to convert/unzip/etc to get the image out of the db or will it automagically recognise it as an image? – Chris O'Brien May 20 '13 at 17:51
  • What technologies are you using for front-end to upload the image? – JamesB May 20 '13 at 17:53
  • The front end is using java servlets and the – Chris O'Brien May 20 '13 at 17:54
0

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?

Mehdi Bouzidi
  • 1,937
  • 3
  • 15
  • 31
Chris O'Brien
  • 372
  • 6
  • 25