uploadFile primefaces

Asked

Viewed 55 times

0

The method below, along with my jsf, uploads a file. bat to a folder inside my project, until then it works normal, the problem is that when I go to see the folder where the file is, it is there, only with 0kb, I open it and there is nothing, someone knows how to solve? Down with my method:

  public void handleFileUpload(FileUploadEvent event) throws SQLException {
        this.arquivo = event.getFile();
        DirControle dir = new DirControle();
        String directory = dir.selectedDir_CB().toString().replace("[", "").replace("]", "");
        String nomeArquivo =arquivo.getFileName();
        try {

            byte[] arq = arquivo.getContents();

            File file = new File(directory +"\\"+getDestino()+ "\\" + nomeArquivo);

            try ( // esse trecho grava o arquivo no diretório
                FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(arq);
                fos.flush();
                fos.close();
                FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, message); // mensagem pra saber se ouve sucesso

            }

        } catch (Exception ex) {

            ex.printStackTrace();
            System.out.println(ex);
        }

meu form de upload:

<h:form class="upload" >
                            <p:fileUpload fileUploadListener="#{upload_file.handleFileUpload}" mode="advanced" dragDropSupport="false"
                                          multiple="true" update="messages" sizeLimit="100000" fileLimit="100" allowTypes="/(\.|\/#_)(gif|jpe?g|png|bat|rar)$/"
                                          />

                            <p:growl id="messages" showDetail="true" />
                        </h:form>

1 answer

0

It worked for me, doing it this way, see if it solves your problem.

ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
String realPath = context.getRealPath("/");
File file = new File(realPath + "/import/");
if (!file.exists())
{
    file.mkdirs();
}

byte[] arquivoByte;

try (FileInputStream fileInputStream = (FileInputStream) event.getFile().getInputstream())
{
    arquivoByte = new byte[(int) event.getFile().getSize()];
    fileInputStream.read(arquivoByte);
}

String fileName = realPath + "/import/" + event.getFile().getFileName();
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(arquivoByte);
fileOutputStream.flush();
fileOutputStream.close();

Browser other questions tagged

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