1

I am trying to trigger a file upload as soon a user navigates to the /uploads route on my website. The upload buttons all work and trigger as expected. However, I cannot seem to programmatically get the input[type=file] to work.

I am really hoping this is possible, but I feel it isn't because of security or something. :(

Anyway, I created this demo as a minimum code example:

class Hello extends React.Component {
  componentDidMount() {
    console.log('this won\'t trigger')
    this._test.click()
    
    setTimeout(() => {
      console.log('this also won\'t trigger')
      this._test.click()
    }, 5000);
  }
  clickInput() {
    console.log('this will trigger')
    this._test.click()
  }
  render() {
    return (
      <div>
        <input 
          ref={(test) => this._test = test}
          name="test"
          type="file"
          multiple={this.props.multiple}
        />
        <button 
          type="button"
          onClick={this.clickInput.bind(this)}
        >
          Trigger upload
        </button>
      </div>
    );
  }
};

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container"></div>
Cœur
  • 37,241
  • 25
  • 195
  • 267
S.Kiers
  • 4,086
  • 3
  • 32
  • 38

1 Answers1

1

User action is required to render Choose File dialog from click or change event at <input type="file"> element.

guest271314
  • 1
  • 15
  • 104
  • 177
  • That is what I was afraid of. Follow up, if they are clicking a link on a prior page, which triggers a react router change, which triggers the file upload; can I somehow preserve that user input (the original link change) to do the trigger? – S.Kiers Mar 22 '17 at 20:38
  • 1
    It is possible to chain click event to open Choose File dialog. See http://stackoverflow.com/a/41336449/, http://stackoverflow.com/questions/29728705/trigger-click-on-input-file-on-asynchronous-ajax-done – guest271314 Mar 22 '17 at 20:53
  • thanks for that answer. That is what I was looking for. :) – S.Kiers Mar 22 '17 at 21:22