How to retrieve the image in a form? - javascript

Hello !
Context
I created products using a form where I ask the admin to give obligatorily: a name, a price ... an image
This is what the form looks like :
I only save the name of the image in my database under the "PRO_URL" column
I manage very well to retrieve my image on my home page showing all the available products.
The admin also has the option to modify a product, to do this, I use the same form as to create a product.
I manage to recover in my fields thanks to "value" the values ​​of the product EXCEPT the image.
Again this is what the form looks like with the data in it :
The file input is still empty.
To send the product information to my form, I send it via a React-router Link containing in the URL the id of the product to be modified.
And I get it all like this :
useEffect(() => {
if (id) {
getProduitById(id).then(response => {
if (response.data){
setProduit({
nom: response.data.nom,
prix: response.data.prix,
description: response.data.description,
imageurl: response.data.imageurl,
qtestock: response.data.qtestock,
marqueId: response.data.marqueId,
})
}
}).catch(err => console.log(err));
}
}, [])
Each product image is stored in my project under public, UUID renames them to be unique :
I read that the input element of type file is uncontrolled so that the site cannot take the image on our computer.
As I save the image there must be a way so that I can use the url or name of my image for my modified product

If you want the image to render on frontend without getting response from backend you can do it like this
URL.createObjectURL(e.target.files[0])
Otherwise if your want to render image from response you need to first generate URL of your image. You can do this by using any cloud service where you upload you file at backend and then get that URL i.e CLOUDINARY, our you can use MULTER to save file in you project directory and generate URL or try other npm packages.

Related

Save and display images in React

I have a profile to keep data from the user, and he can edit when he want. To keep the session, I pass some info from the user in localStorage, because in this project we don't use a library like redux, and one of these fields is "picture" to represent the photo in user's profile.
The problem consists when I try to "save" the image in the localStorage, when I upload the input and save it, it's ok, the picture saves in the database, and in localStorage that link (where the picture is hosted in the db) is correct, but if I try to edit some other field, like "name" for example and I click to apply the changes, the picture should be the same that I save previously, but the result is a file object and the url is not found in the database. It's like that object file replace that field in the localStorage.
Here I detach some lines of the code to guide me a little.
When I have a succesfull login, I saved the picture from data supplied from the api. PictureURL concat the url from the api with the picture URL that I received from the call.
------------
localStorage.setItem("picture", pictureURL);
------------
In my profile component, I have a state that initially load all the data from the localStorage, picture included. This state I'll use later to send the user to the api
const [userState, setUserState] = useState({
--------------------------------
picture: localStorage.getItem("picture"),
------------------
});
Then in my component, I have an input to upload the new image that I want to change
<Input
type={"file"}
size={"sm"}
mt={"10%"}
ml={25}
accept="image/*"
onChange={imageChange}
></Input>
imageChange is a function that consists in read the file, with FileReader, store the result in another state call imgData (that functionality is to show a preview of that image), and then set the picture in the main state userState that I mentioned before
const imageChange = (e) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
setImgData(reader.result);
});
reader.readAsDataURL(e.target.files[0]);
setUserState({ ...userState, picture: e.target.files[0] });
};
And finally, I have a handler to pass all the data from the userState to a formData and send to the api, and when it's all ok, set the localStorage fields with the new data
---------------------------
localStorage.setItem("picture", userState.picture);
---------------------------
Sorry if it's too long, but I don't know where I have the error, maybe when I manage the picture at the beginning, or it's a problem in the backend, but idk! I have 3 days with this problem and I can't see what's going on.
First of all, thanks a lot for the help. All the critics to become more "clean" and to grow up are welcome :)

How to upload Bulk amount of json data with images to the firebase realtime and storage respectively

I have a bulk amount of data in CSV format. I am able to upload that data with python by converting them to the dictionary (dict) with loop. the whole data is getting uploaded.
but now I want to upload bulk data to firebase and images to storage and I want to link between each document and image because i am working on e-commerce react app. so that I can retrieve documents along with images.
which is a good way to do this? should I do this with javascript or python?
I uploaded data manually to firebase by importing from there but again I am unable to upload bulk images to storage and also unable to create references between them. please give me a source where I can find this solution
This is tough, because it's hard to fully understand how exactly your images and CSV's are linked, but generally if you need to link something to items stored in Firebase, you can get a link either manually (go into storage, click and item, and the 'Name' Field on the right hand side is a link), or you can get it when you upload it. So for example, I have my images stored in firebase, and a postgres database with a table storing the locations. In my API (Express), when I post the image to blob storage, I create the URL of the item, and post that as an entry in my table, as well as setting it to be the blobs name. I'll put the code here, but obviously it's a completely different architecture to your problem, so i'll try and highlight the important bits (it's also JS, not Python, sorry!):
const uploadFile = async () => {
var filename = "" + v4.v4() + ".png"; //uses the uuid library to create a unique value
const options = {
destination: filename,
resumable: true,
validation: "crc32c",
metadata: {
metadata: {
firebaseStorageDownloadTokens: v4.v4(),
},
},
};
storage
.bucket(bucketName)
.upload(localFilename, options, function (err, file) {});
pg.connect(connectionString, function (err, client, done) {
client.query(
`INSERT INTO table (image_location) VALUES ('${filename}')`, //inserts the filename we set earlier into the postgres table
function (err, result) {
done();
if (err) return console.error(err);
console.log(result.rows.length);
}
);
});
console.log(`${filename} uploaded to ${bucketName}.`);
};
Once you have a reference between the two like this, you can just get the one in the table first, then use that to pull in the other one using the location you have stored.

How to save text fields values along with file uploads using single api in node js?

I've a use case, in which I need to save registration form field values to the data base and also upload the user image too.
According to my knowledge, I need to use 2 different apis for storing form field values and one for uploading file. As images uploaded like, request.files and raw data be like, request.body.
Is it possible to upload both images and form field values in a single api? I need to get the id of user so that I can map the userId to the image.
Yes, it is possible to do that.
For image you can use it multer to store image(file), and form value can be stored as well.
For multer reference you can visit link
You have to use multer as a middleware as I have used in my router
router.post('/addtype', upload.single("image"), (req, res) => {
const newExample = new Example ({
examplename: req.body.name,
imagePath:'/images/' + req.file.filename
})
newExample .save()
.then(result => {
res.json(result)
})
.catch(error => {
console.log(error)
})
})
I'm using mongoose in this example you can do same with mongodbClient

Best approach/design to web application?

I have been taking a Node.js course on Udemy and would like to apply some of the knowledge I have gained to create a simple web application. I would like to have a user register, which leads him to an admin panel, this part I already have.
This user (requester) can then refer users (invitees) to this website using a unique link. For example he would click a button to generate a unique hyperlink (my idea for this link was to be the http://websiteurl/userid of the requester who is sending the link).
The requester can then send this link through email to their friends to invite them to the website, once they click the link they are taken to a sign up form and when they fill in the form they are linked (added to an array under the original user).
How would I go about setting up this "session", as in make sure that the form that the invitees fill out is linked to the original requester? How can those forms be generated dynamically on the requester's hyperlink?
I'm not looking for the exact code to do this, but rather validation if my idea for the url is a good approach or if there are other approaches I should consider.
Thanks in advance!
Well, this would require you changing the schema for your database. A user will need to have a property like:
{
referred: []
}
The referred array should contain ids or some sort of reference to a user's referred users.
On the "/:userid" route, the form should submit to the route where a new user is created and have a parameter with the user ID. In this case, I am using query parameters.
So if a person were to visit /foo, they would get a form that would post to a URL like /new?userid=foo.
In that route, you can do something like this (assuming Express):
app.post("/new", (req, res) => {
const userID = req.query.userid;
const newUser = // create user normally
if(userID) {
// `userID` referred this user
const referrer = getUser(userID);
referrer.referred.push(newUser);
save(referrer);
}
});
The getUser function should returning the current user, and you should modify the referred property with the new user. This code was merely an outline and you should update the user in your database.
In a nutshell, a form should post to /new?userid=foo, and when creating a new user, if this parameter is present, you can update the database entry for the user id in the parameter with the id of the new user.

Add a custom property to GridFS Meteor FS file during upload

I'm currently creating a file upload and display feature for a web app.
I need to add a custom property (e.g accountID) so that I can later display only the images belonging to a specific account.
I'm using cfs:standard-packages with gridfs to upload/store my images.
I believe I need to add a beforeWrite function to the FS.Store but am unsure how to go about it.
The easiest way to do this is to immediately update the inserted object as follows:
var fileId = MyFiles.insert(file);
MyFiles.update({ _id: fileId },{ $set: { accountId: myAccountId }});
Note that the actual upload of the file object to the store will be asynchronous but you'll get the _id back synchronously and immediately.

Categories