2

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>

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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?
It is possible to chain click event to open Choose File dialog. See stackoverflow.com/a/41336449, stackoverflow.com/questions/29728705/…
thanks for that answer. That is what I was looking for. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.