0

I have a form:

<CustomInput onChange={this.handleUpload} label={this.state.picture.name} type="file" accept="image/*" />

I am able to accept only image files successfully. I am trying to find a way to only accept image files of a certain size, like 50K. I have a Node backend. Is there a way to only accept images of a certain size and specify that from the front end?

Chris Simmons
  • 249
  • 2
  • 7
  • 19

2 Answers2

0

I would solve this by inspecting the Content-Length header in the HTTP request that is sent to your Node server with the image. You can specify in the front end what size your server accepts and check the size when the user sends the image. Your check would compare the number of bytes to the size limit that your are enforcing.

nfadili
  • 1,232
  • 2
  • 8
  • 9
  • Hey nfadili, how can I specify in the front end what size the server accepts? At least, what would that be called so that I can research it? – Chris Simmons Sep 27 '18 at 22:19
0

The following answer addresses the front-end component of your question. See https://stackoverflow.com/a/34698643/3105371 about the back-end component of your question. You may want to open another question specific to your needs on the server. If you do, be sure you include information about your server environment. (expressjs, relevant middleware, etc.)

HTML 5.1 recommendation defines an interface for file inputs. See <input type="file"> on MDN. Looking at the compatibility table on MDN, this looks to be supported by modern browsers. Be sure to test before checking the change into production.

The file input has a files attribute which is a FileList. A FileList is a collection of File objects which expose a size property—the size of the file in bytes.

In the following example, the <CustomInput type="file" /> is passed an onChange prop which is a function that validates for file size.

Run code example at https://stackblitz.com/edit/so-reactstrap-file-input?embed=1&file=Example.js

export default class Example extends Component {  
  state = {
    fileName: '',
    invalidFile: false,
  }
  handleFileChange = this.handleFileChange.bind(this);

  handleFileChange({target: {files}}) {
    const cancel = !files.length;
    if (cancel) return;

    const [{ size, name }] = files;
    const maxSize = 50000;

    if (size < maxSize) {
      this.setState({ fileName: name, invalidFile: false })
    } else {
      this.setState({ fileName: '', invalidFile: true })
    }
  }

  render() {
    const { fileName, invalidFile } = this.state;
    return (
      <FormGroup>
        <CustomInput
          type="file"
          id="exampleCustomFileBrowser"
          name="customFile"
          label={fileName || 'choose an image file'}
          onChange={this.handleFileChange}
          invalid={invalidFile} />
      </FormGroup>
    );
  }
}
webprojohn
  • 958
  • 7
  • 14