S.Kiers
S.Kiers

Reputation: 4206

How can I trigger input[type="file"] programmatically with no actual click involved?

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>

Upvotes: 1

Views: 1518

Answers (1)

guest271314
guest271314

Reputation: 1

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

Upvotes: 1

Related Questions