Node.js 如何显示来自服务器节点的图像?
我的图像已成功上载到/myshop/uploads/文件夹,但我很难将图像加载到浏览器。 这是我的服务器端代码Node.js 如何显示来自服务器节点的图像?,node.js,Node.js,我的图像已成功上载到/myshop/uploads/文件夹,但我很难将图像加载到浏览器。 这是我的服务器端代码 const storage = multer.diskStorage({ destination: (req, file, callBack) => { callBack(null, 'uploads') }, filename: (req, file, callBack) =>
const storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, 'uploads')
},
filename: (req, file, callBack) => {
callBack(null, Date.now() + '-'+ file.originalname)
}
})
var upload = multer({storage: storage})
//Upload image
app.post('/api/myshop/photo', upload.single('file'),(req, res, next)=>{
const file = req.file
console.log(req.file.filename);
if(!file){
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send(file)
});
要将文件发送回客户端,可以使用方法。您需要提供文件的路径
//Upload image
app.post('/api/myshop/photo', upload.single('file'),(req, res, next)=>{
const file = req.file
console.log(req.file.filename);
if(!file){
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
// send file back to client
const filePath = req.file.path;
res.sendFile(filePath);
});
感谢您的支持,使用它我得到了如下图像的路径“uploads/1621755676022-clipart2934035.png”。我尝试使用“”加载图像,但显示“无法获取”错误,您是否已将express app配置为在“上载”目录中提供静态文件?类似这样的
app.use(express.static('uploads'))
。然后尝试http://52.75.82.205:3000/1621755676022-clipart2934035.png