-1

This is my little problem, when i'm trying to get the value from my input of type="file".

this is how i'm doing:

<tr ng-repeat="imagenDatos in tableImagenesPunto | filter: busquedaDatosPunto " >
  <td>PNG</td>
  <td>{{imagenDatos.id_puntoEmpresa}}</td>
  <td>{{imagenDatos.nombre_punto}}</td>
  <td>{{imagenDatos.direccion_punto}}</td>
  <td>
   <input type="file" name="uploadFile[]" id="inputFileServer" accept="image/png" ng-click="inputChange()" />
  </td>
  <td>{{imagenDatos.ruta_punto}}</td>
  <td>
   <button type="submit" class="btn btn-info btn-sm "  value="Upload3" ng-click="uploadFile()" id="btnSubirArchivo" role="button" data-original-title="Subir Logo">
                         <span class="glyphicon glyphicon-open-file" aria-hidden="true"></span>
   </button>
   </td>
 </tr>

And this is on the JS

$scope.uploadFile = function()
{
 var file = document.getElementById('inputFileServer').files[0];
 console.log(file);
}

The results is "undefined", how can i know what is wrong with that?

jecorrales
  • 270
  • 4
  • 21

1 Answers1

1

You are probably reading the files before the user has uploaded a file. Try validating files.length before accessing files[0]. That would prevent the error.

In the snippet below, I have set a setInterval that prints the count of files every one second. You can see that once the user uploads the file, the count will be updated.

In your application, you can listen to the change event on the input, and then based on file length validation, you can access it.

var files = document.getElementById('inputFileServer').files;

setInterval(function() {
  files = document.getElementById('inputFileServer').files;
  console.log("Number of files: ", files.length);
}, 1000);

function inputChange() {
  alert("Input changes");
}
<input type="file" name="fileToUpload[]" id="inputFileServer" accept="image/png" onchange="inputChange()" />
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • @epascarello I thought of showing the file length validation. Also, I just added the change event so that they can read the files once the file is selected. Anything else you can think of? – Nisarg Shah Sep 25 '17 at 17:04
  • The result is Number of files: 0, – jecorrales Sep 25 '17 at 17:08
  • @jecorrales Yes, so when the number of files is zero, it means no file has been uploaded yet. But when you upload a file, it will give you the count 1. Meaning, once that count is greater than zero, you can access the first file like `files[0]`. – Nisarg Shah Sep 25 '17 at 17:10
  • I've updated my question, and i'm getting that result, something is wrong, it takes like the file is not selected. – jecorrales Sep 25 '17 at 17:26
  • `ng-click` is triggered when the user clicks on the input to select a file. So your code is executed by the time user selects the file. You should be using the `onchange` event. See [this](https://stackoverflow.com/a/17923521/5894241) for more details. – Nisarg Shah Sep 25 '17 at 17:30