这个在angular客户端上显示图像的问题困扰了我很久,甚至在看了很多类似的问题之后也是如此。文件成功上载到上载文件夹,文件详细信息存储在mongodb数据库中。
这是angular Client。加载图像数据服务或出厂后的angular V1.6。
$scope.attachImages.push({
name: attachment.originalName,
filePath:attachment.upload_path
})
那么html网页就有了这一点,我使用ng-src作为图像上传路径。
<div layout = "column" ng-repeat ="image in attachImages">
<h5>{{image.name}}</h5>
<img ng-src="{{image.filePath}}"/>
</div>
但我得到的错误是它无法加载图像:
获取http://localhost:3010/client/upload/attachment/lion.jpg 404(找不到)
这是我在express nodejs后端服务器上所做的
router.get('/attachments/:cardId', function(req,res){
//load teh attachemnts from the db... imageId,
/// To get all the images/files stored in MongoDB
Attachment.find({card: req.params.cardId}, function(err,images){
if (err) {
res.json({"success": false, "message": 'Error finding the attachments'})
} else {
res.json({"success": true, "message": images})
//对于单个图像..router.get(“/attachments/:CarDID/:attachmentID”,function(req,res){
Attachment.findOne({_id: req.params.attachmentId}, function(err, image){
if (err) {
res.json({"success": false, "message": 'ERror in finding the image'})
} else {
if (image) { //atleast there z content
//set the content-type correctly so our client or browser know how to handle it.
res.setHeader('Content-Type', image.mime);
//fs.createReadStream(path.join(UPLOAD_PATH, result.filename)).pipe(res);
//fs.createReadStream(path.join()).pipe(res);
res.send(image.upload_path);
}else {
res.json({"success": true, "message": 'No image data found'})
}
}
})
});
如有任何帮助,我们将不胜感激...然后稍后我将讨论createObjectURL方法,它除了杂乱无章的数组数据之外不显示任何内容。
我意识到我在加载图像时在文件路径上犯了一个错误。在发送图像之前,最好先测试一下是否可以在浏览器中从它们的上传路径加载图像。只是在加载路由之前放入这个express静态处理程序,在努力加载图像一周之后,我就得救了。
app.use(express.static(__dirname + '/client'));
app.use(express.static(__dirname + '/client/upload/attachment'));
然后加载快速路由
//var user = require('./routes/user') //user routes
board = require('./routes/board'),
然后在angular客户端上
if(attachName.match(/\.(jpg|jpeg|gif|png)$/)){ //u borrowed this from helper in nodejs
//console.log('yeah it z the image')
//$scope.attachImages.push(attachment);
$scope.attachImages.push({
name: attachment.originalName,
imageUrl: attachment.upload_path
})