I'm currently working on a ReactJS web app. I'm trying to upload a images to a folder and store the filename in the database so I can work with it.
Everything works so far, but my only blockade is the file transfer to the folder.
Here the ImageUpload component:
import * as React from 'react';
export class ImageUpload extends React.Component<any, any> {
constructor(props : any) {
super(props);
this.state = { file: '', imagePreviewUrl: '' };
}
_handleSubmit(e : any) {
e.preventDefault();
// TODO: do something with -> this.state.file
alert(this.state.file.name);
this.state.file.copy("C:\\Documents");
}
_handleImageChange(e : any) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
file: file,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file)
}
render() {
let { imagePreviewUrl } = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<img src={imagePreviewUrl} />);
} else {
$imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
}
return (
<div className="previewComponent">
<form onSubmit={(e) => this._handleSubmit(e)}>
<input className="fileInput"
type="file"
onChange={(e) => this._handleImageChange(e)} />
<button className="submitButton"
type="submit"
onClick={(e) => this._handleSubmit(e)}>Upload Image</button>
</form>
<div className="imgPreview">
{$imagePreview}
</div>
</div>
)
}
}
If you want to upload an image and save it to database, you need an API which will accept FormData, see Form Data Usage, then on the server you will need to save that file to destination. For that you could use ExpressJS and middleware to handle multipart upload - from there you can use NodeJS functions to save file to local destination.
It's not possible to do using only react.