Home > database >  upload image path to mysql along with the user name who uploads the image
upload image path to mysql along with the user name who uploads the image

Time:10-18

i have created one dB that stores URL and name of the images in MySQL and NodeJS and react, I have a login function with node and react. what I want is when user uploads images I want to store it under the user so only he can view that. can you guide me how to achieve this

CodePudding user response:

One of the ways you can achieve this is by managing permissions. Keep a track of who is uploading it.

Uploads
--------
id
path
filename
uid (user_id)

Use this to get image details. To increase security, either set filenames to be random characters or manage server file permissions.

CodePudding user response:

MySql: I assume you have user table and uploads table in MySql. In your uploads table, add created_by column which should be foreign key reference on user_id column from user table.

React: While making call to NodeJs to fetch images, send user_id parameter from React.

Nodejs: Then NodeJs should get only images from Uploads table that are created by the current user by querying MySQL with below query

select <YOUR COLUMNS> from UPLOADS where created_by=user_id

CodePudding user response:

So if you are posting the uploading file's data to the server, for example as a multipart then just add the data to the ajax request.

<input id="upload_file" name="upload_file"/>
// create form data holder
var fd = new FormData();
// add images, text or any data you would like here.
// this will access the upload_files file input element, get the total files selected
let total_files = document.getElementById('upload_file').files.length;
// this will loop through each selected file and add it to the FormData which will be submitted.
for(let i=0;i<total_files;i  ){
    fd.append("upload_file[]", document.getElementById('upload_file').files);
}
// added the users details.
let userID = 1;
let userName = "John Doe"
fd.append("userID", userId);
fd.append("userName", userName);
// make hhtp post request and return the json response.
let api_url = "/api/url/goes/here";
let response = fetch(api_url, {
    headers: {
        "Content-Type": "multipart/form-data",
        "Accept": "application/json",
        "X-Requested-With": "XMLHttpRequest",
    },
    method: 'POST',
    credentials: "same-origin",
    body: fd,
})
.then((response)=>response.json())
.then((responseJson)=>{return responseJson});


// now you can access the response data via the response variable.
  • Related