node.js - 如何显示来自服务器 Nodejs 的图像?
问题描述
我的图片成功上传到 /myshop/uploads/ 文件夹,但我很难将图片加载到浏览器。这是我的服务器端代码
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)
});
解决方案
要将文件发送回客户端,可以使用sendFile方法。您需要提供文件的路径。
//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);
});
推荐阅读
- php - 当我尝试重命名图像时出现路径问题
- javascript - React HOC 和 TypeScript 3.2
- kubernetes-helm - 如何触发 helm 中呈现的 configmap 的 sha256sum 更改?
- oracle-sqldeveloper - Oracle:使用本机动态 SQL 获取包含 x 的方案
- internet-explorer-11 - Web 服务器 IE11 图像显示为黑框白色十字 - 它是内容类型吗?
- javascript - 获取 mongo shell BinData 作为字符串
- javascript - 加载javascript后如何从URL获取HTML代码
- laravel - 使用带()和不带()的模型方法有什么区别?
- python - 使用先前声明的值在 pandas 数据框中附加行
- mongodb - VS Code、Azure Cosmos DB 和 MongoDB 的问题