i am creating an ecommerce website using NextJs. i want to give admin rights where admin can upload an product image which will be displayed later on dashboard along with the product.
My question is how to achieve this?? i can store the image location in db along with other product details but what about image?? where to store this uplaoded image so that it can be automatically displayed on page load.
one way would be to load images in file system where app is served but then i would have to deploy app again and again and this seems impractical. Also i dont think there is way to directly load images to public folder.
Looking forward to answers.
thanks
You basically do it like you would do it in React. Create a component which handles the displaying of the preview as well as the upload to an external server. I created a codepen for you to test the component in the wild. It consists of this:
import React from "react";
const ImageUpload = props => {
const [currentFile, setFile] = React.useState();
const [previewImage, setPreview] = React.useState();
const [success, setSuccess] = React.useState(false);
const selectFile = function (e) {
setFile(e.target.files[0]);
let reader = new FileReader();
reader.onloadend = () => {
setPreview(reader.result);
};
reader.readAsDataURL(e.target.files[0]);
};
const submit = function () {
let fd = new FormData();
fd.append("file", currentFile);
let request = new XMLHttpRequest();
request.onreadystatechange = function (state) {
if (
state.originalTarget.readyState === 4 &&
state.originalTarget.status === 200
) {
setSuccess(true);
}
};
request.open(
"POST",
"https://us-central1-tutorial-e6ea7.cloudfunctions.net/fileUpload",
true
);
request.send(fd);
};
return (
<div>
<h1>Upload an image</h1>
<input type="file" accept="image/*" onChange={selectFile} />
{previewImage && !success && (
<div>
<img className="preview" src={previewImage} alt="" />
</div>
)}
{success && <div>Image successfully uploaded</div>}
<button onClick={submit}>Upload</button>
</div>
);
};
export default ImageUpload;
An <img/>
element which accepts files and renders a preview in an onChange
event using the FileReader api.
A submit
function which uses the FormData interface to append the image and uses XMLHttpRequest to upload the file to the server.
Some simple UI logic to display the preview to the user.
Check out this tutorial for a more detailed explanation.