Мне удалось загрузить файл в React JS и сохранить его в общей папке NodeJS, я также храню их в базе данных (только имена файлов)
Что я пытаюсь сделать сейчас, когда мои файлы загружены, как я могу получить файлы с сервера (или базы данных или обоих).
Моя функция загрузки в интерфейсе выглядит следующим образом:
onSubmit = (event) => {
//some security here so i make sure that the upload is an valid image
//I am uploading Ads for my page
const data=new FormData();
data.append('adimage',adimage);
data.append('adurl',adurl);
fetch('http://localhost:3001/uploadad',{
method:'POST',
body:data,
}).then((response)=>{
response.json().then(ad=>{
let ads=this.state.ads;
ads=[...ads,ad.file];
this.setState({ads:ads});
})
.catch(err=>console.log('failed to upload image'));
}).catch(err=>console.log('error uploading image'));
И серверная часть NodeJS:
const uploadAd= (req,res,db,urlExists)=>{
//some security here so i make sure that the upload is an valid image
db('ads')
.insert({
image: ad.name,
url: adurl
})
.returning('id')
.then(id => {
db('ads').update({
image: `ad${id[0]}.${ext}`
})
//just want to store all ad images as ad{adid}
.where('id', '=', id[0])
.returning(['image', 'url'])
.then(data => {
let img = data[0].image;
let url = data[0].url;
const reqPath = path.join(__dirname, '..\\..\\');
//uploading the file to the public folder
ad.mv(`${reqPath}/public/${img}`, (err) =>{
if (err) {
return res.status(500).send(err);
}
res.json({
file: `${img}`,
url: url
});
});
}).catch(err => console.log(err));
}).catch(err => console.log(err));
};
Теперь, когда мои файлы хранятся в папке на стороне сервера, как я могу получить данные на стороне клиента?
Могу ли я просто сохранить их в своей базе данных без необходимости загружать файлы, но откуда я знаю, что это не очень хорошая практика?
Я довольно новичок, чтобы реагировать и нодить, и это мой первый пост здесь. Спасибо