Search code examples
javascriptpolymerweb-component

Access file selected with paper-input


I'm trying to upload a file chosen through a Polymer <paper-input type="file" id="filepicker"> element but when i try to access the file with:

var file = this.$.filepicker.files

i get a files is not defined error.

I haven't found any other methods to access files in paper inputs so I'm not sure what the problem is here.

Any help would be appreciated!


Solution

  • The files property is found on the inner <input> element of <paper-input>, which you could access with <paper-input>.inputElement.inputElement. So you would use this:

    this.$.filepicker.inputElement.inputElement.files[0];
    

    Note: In earlier versions of <paper-input>, the inner <input> was accessed with this.$.filepicker.inputElement, but it has since been refactored to have another container (hence, this.$.filepicker.inputElement.inputElement).

    HTMLImports.whenReady(() => {
      Polymer({
        is: 'x-foo',
        _handleFiles: function() {
          console.log(this.$.input.inputElement.inputElement.files[0]);
        }
      });
    });
    <head>
      <base href="https://polygit.org/polymer+1.10.1/components/">
      <script src="webcomponentsjs/webcomponents-lite.js"></script>
      <link rel="import" href="polymer/polymer.html">
      <link rel="import" href="paper-input/paper-input.html">
    </head>
    <body>
      <x-foo></x-foo>
    
      <dom-module id="x-foo">
        <template>
          <paper-input type="file" id="input"></paper-input>
          <button on-tap="_handleFiles">Log file info</button>
        </template>
      </dom-module>
    </body>

    codepen