uploadFile primefaces

0

The method below, along with my jsf, uploads a .bat file to a folder inside my project, until it works normally, 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 have nothing, does anyone know how to solve? Below 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>
    
asked by anonymous 23.09.2016 / 01:17

1 answer

0

For me it worked, doing this, 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();
    
04.10.2016 / 15:34