Image upload with Primefaces on Tomcat server, only the image path being saved in the database

Asked

Viewed 1,964 times

4

Fala galera.

I’m a beginner in Java and am doing a small Dynamic Web project using Primefaces, JSP, Hibernate and Tomcat. Basically it is several forms of registration and one of them is the registration of users. The Domain, Bean, DAO part and the pages to list, register, edit and delete are already working, but the user table has a field for photo(image), and that’s where my problem is. I want to save only the Photo(image) path in the database, and in the user page I want to let them add your photo, of course. I read a lot of things on Google about how to do using the component p:fileUpload, And I confess I succeeded, in part. The problem is, I want the images to be saved in the right way, for example in a folder /images in my project.

The way I’m doing it now is like this: No Bean

public void upload(FileUploadEvent event) {

    try {
        String realPath = FacesContext.getCurrentInstance()
                .getExternalContext().getRealPath("/");

        // Aqui cria o diretorio caso não exista
        File file = new File(realPath + "/imagens/");
        file.mkdirs();

        byte[] arquivo = event.getFile().getContents();
        String caminho = realPath + "/imagens/"
                + event.getFile().getFileName();

        // esse trecho grava o arquivo no diretório
        FileOutputStream fos = new FileOutputStream(caminho);
        fos.write(arquivo);
        fos.close();

        pathImage = caminho;
        System.out.println("caminho da imagem salva é  = " + caminho);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}`

In the file . xhtml

                    <p:fileUpload fileUploadListener="#{checksPicosBean.upload}" fileLimit="1"
                    fileLimitMessage="Excedido Limite de arquivos"
                    cancelLabel="Cancelar" label="Arquivo" uploadLabel="Anexar"
                    invalidFileMessage="Somente arquivos .jpg, .png ou .gif"
                    allowTypes="/(\.|\/)(gif|jpe?g|png)$/" value="#{checksPicosBean.imagem}"
                    mode="advanced" skinSimple="true" />

The problem is that it is saving in a folder on my disk c: and not in a supposed server folder. What would be the right way to make this happen? Is there any configuration in Tomcat that has to be done? I intend to make these forms available on the web, so I’d like to know what the right way is to make it work.

  • How is the path currently being saved? The recommended would be to write to some server directory reserved for this, and out of context of the application.

  • Saito is absolutely right, saving images inside the application is only for static images, the correct thing is to benefit from Tomcat’s virtual directories, where you create a file. xml with project name + old game + directory mapped ex: my-webapp#images.xml, and adds it in Tomcat($TOMCAT_HOME/conf/Catalina/localhost) on the server.xml should work as well, see model

1 answer

2

Thiago, I have a similar application and I do so:

public void upload(FileUploadEvent event)
{
    UploadedFile uf = event.getFile();
    Tools t = new Tools();
    String nomeArq = t.agora()+"-"+t.trataAcentoString(uf.getFileName());
    this.avaliacao.setAnexo_resp(nomeArq);        
    String path = "";
    // aqui verifico se é linux ou windows
    if(System.getProperties().get("os.name").toString().trim().equalsIgnoreCase("Linux"))
    {
        path = "/home/workspace/gca/WebContent/resources/files/";
    }
    else
    {
        path = "c://files//avaliacao//";
    }

    File f = new File(path + nomeArq);
    OutputStream os = null;
    InputStream is = null;
    try
    {
        is = uf.getInputstream();
        byte[] b = new byte[is.available()];
        os = new FileOutputStream(f);
        while(is.read(b) > 0)
        {  
            os.write(b);  
        }
        // aqui você pode colcar a gravação do path no BD

        Tools.msgAlert("Alerta", "O arquivo foi enviado corretamente, clique em enviar para concluir a operação.");
    } 
    catch(IOException ex) 
    {  
        Tools.msgErro("Erro", ex.getMessage());  
    } 
    finally 
    {  
        try 
        {  
            os.flush();  
            os.close();  
            is.close();  
        } 
        catch(IOException ex) 
        {  
            Tools.msgErro("Erro", ex.getMessage());
        }  
    }
}

Note the comments in the code, because I check before if I am on my machine (development) or on the server (production) and only then write the file passing the complete path to save in the bank.

gca is the name of the application, I can write either inside the project or where I want to pass the full path.

  • Good evening Aragon. Where does this Tools Class come from and this t.agora method()? I tried instating it but I only have the Tool Class available.

  • Another question. When I put this project on a server on the web, this folder (for example the path variable = "c://files//evaluation//"; passed by you) where will be saved the images to be changed in the 'hand'? Or could I create a relative path, as is normal to do with php for example ?

Browser other questions tagged

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