Uploading photo in java form

1

I need to have my form send and save a photo in the database and then show me how to do it?

I declare what kind of variable in the Client entity? String or byte?

I know the primefaces has a component but I do not know how to do it. Can anyone help me?

    
asked by anonymous 27.09.2016 / 21:12

1 answer

1

If you are using primefaces, probably the best way is to use the same upload file. I think the documentation example is enough to get started. link

You basically need a form with the file upload component.

The object that will be returned to your ManagedBean will be of type UploadFile and through it you can get the bytes, filename among other things for example:

@ManagedBean
public class FileUploadView {

    private UploadedFile file;

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public void upload() {
        if(file != null) {
             System.out.println("Nome do arquivo: " + file.getFileName());
             file.getContents(); //array de bytes
             files.getInputStream();//input stream do arquivo
        }
    }
}

Once you have this file you need to decide how you will store this image. I see two possible solutions:

1 - Store the image bytes in the database:

The first is to save the image in bytes even in a column in the database, in this case it will depend on the database you are using, mysql has the type BLOB for example. In this case your Client entity would have a field of type array of bytes private byte[] foto; . If you are using JPA it is highly recommended that you use the @Lob annotation.

2 - Save the file to a folder:

The other option would be to save this image to a folder (which can be on the same server or on an accessible network location) and save in the bank only the path needed to retrieve this image. In this case your variable would be only a string with the path private String foto .

The second option is usually better due to not storing directly in the database file which can be large by greatly increasing the table size unnecessarily.

    
28.09.2016 / 14:54