Question:
Hey guys.
I'm new to Java and I'm doing a small Dynamic Web project using PrimeFaces, JSP, Hibernate and TomCat. Basically it is about several registration forms and one of them is the user registration. The Domain, Bean, DAO part and the pages to list, register, edit and delete are ready and working, but the user table has a field for photo (image), and that's where my problem is. I want to save only the path of the Photo(image) in the database, and on the user's page I want to let them add their photo, of course. I read a lot on Google about how to do it using the p:fileUpload component, and I confess that I managed to do it, in parts. The problem is, I want the images to be saved the right way, for example in a /images folder 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 .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" />
Problem is that it is saving to a folder on my c: disk and not to a supposed folder on the server. What would be the correct 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 would like to know what the correct way is to make this work.
Answer:
Thiago, I have a similar application and I do it this way:
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 first check if I'm on my machine (development) or on the server (production) and only then I record the file, passing the full path to save it later.
gca is the name of the application, I can record it either inside the project or wherever I want, passing the full path.