Javascript in JSF page - Primeface

Asked

Viewed 722 times

0

HTML code - JAVASCRIPT It reads a txt file from the computer and puts its value in an html input

<input type="file" id="files" name="files[]" multiple />
<input type="text" required name="txtstart" style="width:150px" value="">

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    var saida = "";
    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          saida+=e.target.result;
          document.querySelector("[name='txtstart']").value = saida;
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsBinaryString(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

I want to put this same logic in the first face, but I can’t get the selected file to enter in one p:inputTextarea I tried to do the same in HTML without tags p: but still javascript is not executed.

In short, I need to read a computer file and put its value inside the component below:

<p:inputTextarea value="#{polylinesView.texto}" rows="7" cols="20"
                                     scrollHeight="10" />

1 answer

2


To upload files using primefaces usually uses the file upload component. Here is an example of how it could be written:

<h:form>
<p:fileUpload value="#{beanController.arquivoAula}" sizeLimit="20971520" invalidSizeMessage="Somente são aceitos arquivos de até 20MB"
                    label="Selecionar arquivo" cancelLabel="Cancelar" allowTypes="/(\.|\/)(txt)$/" 
                    invalidFileMessage="Somente são aceitos arquivos dos tipos: txt " 
                    fileUploadListener="#{beanController.handleFileUpload}" process="@form" update="@form" />

                    <p:inputTextarea value="#{cursoController.campoTextArea}">

                    </p:inputTextarea>
</h:form>

The method handleFileUpload should be implemented in your managedbean similar to the one below:

public void handleFileUpload(FileUploadEvent event){
    UploadedFile file = event.getFile();

    byte[] contents = event.getFile().getContents();
    String dados = new String(contents);
    this.campoTextArea = dados;
}

Once the file has been uploaded the data will be read and added in the String campoTextArea that is associated with the textarea in the form.

Following is fileupload documentation link:link

Browser other questions tagged

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