我使用 multer,node.js,mongodb 上传图片。
我在上传文件夹中上传了图片,并将路径存储在 MongoDB 中。
这是我的文件夹结构
服务器正在运行
http://localhost:3000/images/590051dcc90cf702e452b9c1
根据文档id我正在检索文档
// To get the single image/File using id from the MongoDB
app.get('/images/:id', function(req, res) {
//calling the function from index.js class using routes object..
routes.getImageById(req.params.id, function(err, genres) {
if (err) {
throw err;
}
//res.download(genres.path);
res.send(genres)
});
});
我收到了这样的回复
{"_id":"590051dcc90cf702e452b9c1","path":"uploads\login.jpg","name":"asdf","email":"asdf@gmail.com","originalname":"login.jpg","__v":0}
我正在将上述响应发送给 Angular 和 andriod 应用程序。
现在我想以 Angular 显示此图像。
Angular 服务器在不同的服务器上工作 Node 服务器在不同的服务器上工作
我是这样写的
</head><body>
<body ng-controller="RegisterCtrl" ng-app="myApp">
<div ng-init="signin()">
<img ng-src="{{response.path}}"/>
{{response}}
</div>
</body>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js'></script>
<script>var myApp = angular.module('myApp', []);
myApp.controller('RegisterCtrl', function ($scope,$http) {
$scope.signin = function()
{
$http.get('http://localhost:3000/images/590051dcc90cf702e452b9c1').success(function(data, response)
{
$scope.response = data;
console.log(data);
});
}
});
</script>
</body></html>
我遇到了错误
file:///C:/Users/mohan/Desktop/uploads/login.jpg net::ERR_FILE_NOT_FOUND
bcoz文件位于服务器端
最佳答案
在 Node JS 服务器上转换 get api 方法以从 Mongo Db 获取图像路径并返回图像的字节数组。
// To get the single image/File using id from the MongoDB
app.get('/images/:id', function(req, res) {
//calling the function from index.js class using routes object..
routes.getImageById(req.params.id, function(err, genres) {
if (err) {
throw err;
}
//res.download(genres.path);
var fs = require('fs');
// read binary data
var bitmap = fs.readFileSync(genres.path);
// convert binary data to base64 encoded string
//res.send(new Buffer(bitmap).toString('base64'));
genres.path = new Buffer(bitmap).toString('base64');
res.send(genres)
});
});
将此字节数组绑定(bind)到您的标签。
<img ng-src="{{'data:image/png;charset=utf-8;base64,' + response.data.path}}">
关于javascript - 如何以 Angular 显示图像(服务器端上传文件夹中的图像上传和angularjs在不同的服务器上工作)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43631683/