8 October 2019

You can use FormData to send form data using AJAX, including files. This is for you if you have to manually add files, you don't take them from a form, for some reason. This snippet is a react component witch does exactly that.

Source code viewer
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3.  
  4. class MyComponent extends React.PureComponent {
  5. constructor(props) {
  6. super(props);
  7. this.form = React.createRef();
  8. this.filePhoto = React.createRef();
  9. }
  10.  
  11. handleSubmit(event) {
  12. event.preventDefault();
  13. const formData = new FormData(ReactDOM.findDOMNode(this.form.current));
  14. formData.append('file_photo', this.filePhoto.current.files[0]);
  15. }
  16.  
  17. render() {
  18. return <>
  19. <form onSubmit={this.handleSubmit} ref={this.form}>
  20. <input type="submit" value="Submit">
  21. </form>
  22. <input type="file" ref={this.filePhoto} />
  23. </>;
  24. }
  25. }
Programming Language: ECMAScript