Upload photo in java form

Asked

Viewed 791 times

1

I need to make my form send and save a photo in the database and show later, how I should do ?

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

I know the first faces have a component but I don’t know how to do it. Someone can help me ?

inserir a descrição da imagem aqui

1 answer

1

If you are using primefaces, probably the best way is to use the same upload file. I believe the example of documentation is enough to start using. http://www.primefaces.org/showcase/ui/file/upload/basic.xhtml

You basically need a form with the upload file component.

The object that will be returned to your Managedbean will be of the type Uploadfile and through it you can pick up the bytes, file name 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 to store this image. I see two possible solutions:

1 - Store 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 an array of bytes type field private byte[] foto;. If you are using JPA it is recommendable to use the annotation @Lob.

2 - Save the file to a folder:

The other option would be to save this image in a folder (which may be in the same server or in a accessible network location) and save in the database only the necessary way to recover this image. In this case your variable would only be a string with the path private String foto.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.