Javascript 从节点JS(或数据库)获取图像以响应JS
我设法在React JS中上传了一个文件并将其存储在我的NodeJS公用文件夹中,我还将它们存储在一个数据库中(只是文件名)Javascript 从节点JS(或数据库)获取图像以响应JS,javascript,node.js,reactjs,postgresql,knex.js,Javascript,Node.js,Reactjs,Postgresql,Knex.js,我设法在React JS中上传了一个文件并将其存储在我的NodeJS公用文件夹中,我还将它们存储在一个数据库中(只是文件名) 我想做的是,现在我的文件已经上传,我如何从服务器(或数据库或两者)获取文件 我在前端的上传功能如下所示: onSubmit = (event) => { //some security here so i make sure that the upload is an valid image //I am uploading Ads
我想做的是,现在我的文件已经上传,我如何从服务器(或数据库或两者)获取文件
我在前端的上传功能如下所示:
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));
};
现在,我的文件存储在服务器端的文件夹中,如何在客户端获取数据?我可以将它们存储在数据库中而无需上传文件,但据我所知,这不是一个好的做法吗?
我对react和node非常陌生,这是我在这里的第一篇帖子。谢谢您可以将路由添加到节点后端,以提供图像服务;像这样:
http://localhost:3001/img/123
其中节点将读取id 123并发回图像文件。您也在使用node还是express?您有这个${reqPath}/public/${img}
来创建图像的url我也在使用express。在React中,我想获取所有已上传的图像,因为我不完全了解这是如何工作的,我更确切的问题是,我可以从节点中上传的文件夹中获取这些图像吗?因此,我将所有广告作为状态保存在我的广告组件中,现在我只需要将它们作为道具传递给包含该图像的图像组件,然后使用${reqPath}/public/${img}
获取特定图像?我想我可以一次获取所有图像。如果是这样的话,非常感谢,这个问题已经解决了:)不在您的问题范围之内,但是您可能应该在您的设置中添加一个类似s3的服务,或者类似的服务。否则,这些文件会弄乱您的repo,或填充您的服务器,阻塞您的服务器并减慢其他响应。