Pessoal, estou com um problema no FileUpload do primefaces, quando uso o browser IE, consigo pegar o caminho do arquivo por inteiro, mas quando uso o Chrome somente consigo pegar o nome do arquivo, que para gravar esse meu arquivo em banco de dados não dá certo.
Existe alguma forma de funcionar para detectar o caminho e o nome sem essa diferença de browser?
public void AdicionarArquivo(FileUploadEvent event) throws FileNotFoundException, SQLException {
file = event.getFile();
nome_anexo = event.getFile().getFileName();
if (incluirArquivo(file)) {
FacesMessage msg = new FacesMessage("Arquivo", event.getFile().getFileName() + " Anexado com sucesso.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
Pois preciso gravar o nome do arquivo em um campo e o arquivo em si em outro campo, alguem sabe como faço isso independente de browser??
[code]public String converterUTMGeo(){
try{
InputStreamReader isr = new InputStreamReader(file.getInputstream());
BufferedReader in = new BufferedReader(isr);
Fiz o teste de acordo com o teu primeiro exemplo, e infelizmente ele somente me traz com o browser Chrome o nome do arquivo e nao o caminho, já com o IE faz certinho.
Nao existe nenhuma forma de pegar o caminho do arquivo independente do browser e extrair o nome dele, já que vou precisar gravar o nome do arquivo e o arquivo em si.
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
FacesContext aFacesContext = FacesContext.getCurrentInstance();
ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
String realPath = context.getRealPath("/");
// Aqui cria o diretorio caso não exista
File file = new File(realPath + "/uploads/");
file.mkdirs();
byte[] arquivo = event.getFile().getContents();
String caminho = realPath + "/uploads/" + event.getFile().getFileName();
// esse trecho grava o arquivo no diretório
FileOutputStream fos = new FileOutputStream(caminho);
fos.write(arquivo);
fos.close();
Que pega o arquivo upado e copia pra uma pasta no servidor, ficaria facil para saber o caminho depois, o problema é que quando eu uso o String caminho = realPath + "/uploads/" + event.getFile().getFileName(); se for IE vem o caminho inteiro (Ocorrendo um erro) Se for Chrome, vem somente o nome (Dando certo)
[editado]
Até utilizo isso no meu web.xml [uploadDirectory ] indicando um local, mas nao consigo pegar esse caminho pelo event.getFile()…
Tem alguma forma de identificar o browser e se caso for o IE extrair somente o nome do arquivo, para ficar uma rotina (no final dela no caso) que sirva para qualquer tipo de browser?
conseguiu alguma solução amigo? To desenvolvendo uma aplicação em que o caminho do arquivo do lado do cliente é muito importante… e precisava pegá-lo de alguma maneira… se puder me dar uma dica
Cara, eu fiz da seguinte forma, tenho dois metodos, um que adiciona o arquivo e outro que grava o arquivo em uma variavel.
private byte[] bytes_novo = new byte[(int) 0];
public void AdicionarArquivo(FileUploadEvent event) throws FileNotFoundException, SQLException, IOException {
try {
boolean IE = false;
boolean Linux = false;
boolean Chrome = false;
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
FacesContext aFacesContext = FacesContext.getCurrentInstance();
ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
String realPath = context.getRealPath("/");
String nome_real = "";
if (event.getFile().getFileName().lastIndexOf("\\") > 0) { //Windows
nome_real = event.getFile().getFileName().substring(event.getFile().getFileName().lastIndexOf("\\"), event.getFile().getFileName().length());
IE = true;
Linux = false;
} else if (event.getFile().getFileName().lastIndexOf("/") > 0) { //Linux
nome_real = event.getFile().getFileName().substring(event.getFile().getFileName().lastIndexOf("/"), event.getFile().getFileName().length());
IE = true;
Linux = true;
} else {
Chrome = true;
nome_real = event.getFile().getFileName();
}
if (upLoadChamado == null) {
upLoadChamado = new CamposUploadChamado();
}
byte[] arquivo = null;
String caminho = null;
if (IE && Linux == false) { //Quando for Windows e IE
nome_real.replace("\\", " ");
upLoadChamado.setNome_anexo(nome_real.replace("\\", " ").trim());
// Aqui cria o diretorio caso não exista
File file = new File(realPath + "uploads\\");
file.mkdirs();
arquivo = event.getFile().getContents();
caminho = realPath + "uploads\\" + nome_real.trim(); //event.getFile().getFileName();
} else if (IE && Linux) { //Quando for Linux e IE ou Chrome
nome_real.replace("/", " ");
upLoadChamado.setNome_anexo(nome_real.replace("/", " ").trim());
// Aqui cria o diretorio caso não exista
File file = new File(realPath + "uploads/");
file.mkdirs();
arquivo = event.getFile().getContents();
caminho = realPath + "uploads/" + nome_real.trim(); //event.getFile().getFileName();
} else { //Quando for Chrome
nome_real.replace("/", " ");
upLoadChamado.setNome_anexo(nome_real.replace("/", " ").trim());
// Aqui cria o diretorio caso não exista
File file = new File(realPath + "uploads/");
file.mkdirs();
arquivo = event.getFile().getContents();
caminho = realPath + "uploads/" + nome_real.trim(); //event.getFile().getFileName();
}
// esse trecho grava o arquivo no diretório
FileOutputStream fos = new FileOutputStream(caminho);
fos.write(arquivo);
fos.close();
File arquivo_file = new File(caminho);
if (incluirArquivo(arquivo_file)) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Arquivo Anexado com Sucesso: ", upLoadChamado.getNome_anexo()));
}
} catch (Exception ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro ao Copiar Arquivo para Anexo", ex.getMessage()));
return;
}
}
public boolean incluirArquivo(File f) throws FileNotFoundException {
try {
//converte o objeto file em array de bytes
InputStream is = new FileInputStream(f.getPath());
upLoadChamado.setBytes(new byte[(int) f.length()]);
int offset = 0;
int numRead = 0;
while (offset < upLoadChamado.getBytes().length
&& (numRead = is.read(upLoadChamado.getBytes(), offset, upLoadChamado.getBytes().length - offset)) >= 0) {
offset += numRead;
}
bytes_novo = upLoadChamado.getBytes();
is.close();
f.delete(); //Deleta o arquivo onde foi criado
return true;
} catch (IOException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro ao Converter Anexo", ex.getMessage()));
}
return false;
}
Em resumo, para evitar problemas com navegador e tudo mais, eu crio o arquivo em um diretorio local da minha aplicação e depois adiciono ele desse diretorio, e nao direto do diretorio de origem do arquivo.