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>
);
}
}