Image upload with PrimeFaces on TomCat server, being saved only the path of the image in the database

4

Talk to people.

I'm a beginner in Java and I'm doing a small Dynamic Web project using PrimeFaces, JSP, Hibernate and TomCat. Basically it is about several forms of registers and one of them is the register of users. The Domain, Bean, DAO, and the list, register, edit, and delete pages are already up and running, but the user table has a field for the picture, and that's where my problem is. I want to save only the path of the Photo (image) in the database, and in the user page I want to let them add their photo, of course. I read lots of things on Google how to do it using the p: fileUpload component, and I confess I got it in parts. The problem is that I want the images to be saved in the correct way, for example in a folder / images in my project.

The way I'm doing it now looks 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 .xhtml file

                    <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 to a folder on my disk c: and not in a supposed server folder. What would be the correct way to make it happen? Is there any configuration in TomCat that has to be done? I plan to make these forms available on the web, so I'd like to know what the correct way is to make it work.

    
asked by anonymous 10.06.2015 / 03:23

1 answer

2

Thiago, I have a similar application and I do it like this:

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, as I check beforehand if I am on my machine (development) or server (production) and only then I save the file passing the complete path and then save it to the bank.

gca is the name of the application, I can write either within the project or wherever I want by passing the complete path.

    
17.06.2015 / 19:05