FileUpLoad Primefaces - Caminho do arquivo

10 respostas
J

Bom dia,

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??

Obrigado!!

10 Respostas

A

Estranho!! :frowning:
Como esta o caminho do arquivo?

J

Pelo IE: C://temp//arquivo.txt
Pelo Chrome: arquivo.txt

vem diferente usando a mesma prorpriedade

Alguma sugestao?

C

Boa Tarde ...

Eu faço assim ... (Primefaces 2.2, JSF 2.0)

Página XHTML
<p:fileUpload value="#{conversaoCoordenadaBean.file}" mode="simple"/>
                    <h:panelGrid columns="2">
                        <p:commandButton value="Importar" ajax="false"
                            actionListener="#{conversaoCoordenadaBean.upload}" update="messages"/>
                        <h:outputText value="#{conversaoCoordenadaBean.file.fileName}"/>
                    </h:panelGrid>
Bean
public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public void upload() throws IOException {
     try{   
         InputStreamReader isr = new InputStreamReader(file.getInputstream());
         BufferedReader in = new BufferedReader(isr);
         
...

Web.XML

<filter>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>
C

Team Primefaces....

http://forum.primefaces.org/viewtopic.php?f=3&t=24170

Você pode ler e criar outro arquivo ....

Bean
public String converterUTMGeo(){
    try{   
         InputStreamReader isr = new InputStreamReader(file.getInputstream());
         BufferedReader in = new BufferedReader(isr);  
         
         ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); // Context  
         HttpSession session = (HttpSession) context.getSession(false);
         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
         
         //Coordenadas
         double[]coordinatesUTM = new double[2];
         
         outStream.write("COD;X;Y".getBytes());
         
         //Cabeçalho
         String line = in.readLine();                
         while((line = in.readLine()) != null){ 
                          
            String result [] = line.split(";"); 
             
            //Se for Maior que 100
            if(Double.parseDouble(result[1].toString()) > 100){
                coordinatesUTM[0]= Double.parseDouble(result[1].toString());
                coordinatesUTM[1]= Double.parseDouble(result[2].toString());
                coordinatesUTM = ConverteCoordenadas.convertUTMGeo(Integer.parseInt(getSelectedConvertUTMGeo()), coordinatesUTM);
                outStream.write(("\n" + result[0].toString() + ";" + String.valueOf(coordinatesUTM[0]) + ";" + String.valueOf(coordinatesUTM[1])).getBytes()); 
            }else{
                outStream.write(("\nID < " + result[0].toString() + " > com padrão de coordenadas inválido!").getBytes()); 
            }    
         }   
        
         
        in.close(); 
         
        //Passando Parametros via Sessao
        session.setAttribute("arquivo", outStream);
        session.setAttribute("nomeFile", "ConvUTMGeo.txt");
        session.setAttribute("formato", "txt");
        redirect("/DownloadServlet");


        FacesContext.getCurrentInstance().responseComplete();
         
         
        } catch (IOException e) {   
            System.out.println(e);   
        }finally{ 
            return "";
        } 
   }

No meu caso eu crio e efetuo Download invocando minha servlet "DownloadServlet"

J

CLEYSON, desculpa a demora da resposta do post.

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.

**Uso PrimeFaces 3.3

Obrigado!

C

Boa Tarde

O próprio Team Primefaces reconhece incompatibilidade com Navegadores Chrome e Firefox.

Verifica essas dicas …

http://stackoverflow.com/questions/10666370/where-does-pfileupload-save-my-file
http://www.mastertheboss.com/primefaces/primefaces-file-upload-example

Porque você não copia o arquivo do Cliente para uma pasta no servidor :?:

J

Pois é, tenho esse meu codigo aqui:

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?

Obrigado!!

P

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

Obrigado (=

J

Opa

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.

Espero ter ajudado!

P

Vvaleu amigo… vou dar uma olhada :wink:

Abraço!!

Criado 22 de outubro de 2012
Ultima resposta 13 de abr. de 2013
Respostas 10
Participantes 4