NOTE: this is NOT a production application. It is a small app that I am making to explore the capabilities of selecting, opening, saving and reading an image from a DB.
I do not know what method I should call to get the correct Buffer data to store image in mongodb. ( I am aware that mongoDB has a 16mb limit on documents )
In my app, I want the user to be able to select an image from a file on their pc, give the user a preview of the image, then when the user hits submit (not shown here) save the image into mongodb
I know when the user clicks the "choose file" button I can get the file like this:
const file = event.target.files[0]
if (!file) {
// user has hit the cancel button
return;
}
//console.log(file);
I can get information about the file:
console.log(file.type);
console.log(file.size);
and here is how the image is read:
let fr = new FileReader();
fr.readAsDataURL(file);
fr.onload = (e) =>{
this.productImageAdd(e.target.result);
}
This is how the image is stored in the (react) component state
productImageAdd = (file) => {
let temp = this.state["filesArray"] || [];
temp.push(file);
this.setState({"filesArray": temp});
}
Here is the state of my component
this.state = {
filesArray: [],
};
In another component, I get a listing of all the images and then map them to an item for display:
return filesArray.map((file, index) => (
<FileDropZoneItem key={index} id={index} file={file} />
));
In FileDropZoneItem, this is how images are "previewed":
return (
<li className="flex-item ">
<img src={file} width="200" height="200"/>
</li>
);
I saw this stackoverflow question and I am moving towards that to store the image in MongoDB:
Store an image in MongoDB using Node.js/Express and Mongoose
In that post, their schema is like this:
var schema = new Schema({
img: { data: Buffer, contentType: String }
});
And they store the image like this:
var A = mongoose.model('A', schema);
var a = new A;
a.img.data = fs.readFileSync(imgPath);
a.img.contentType = 'image/png';
but I don't really know the difference between fs.readFileSync and fr.readAsDataURL.
Will storing to mongodb work using fr.readAsDataURL or do I need fs.readFileSync ?
I also saw: Difference between readAsBinaryString() and readAsDataURL() in HTML5 FileReader API