如何以angular度显示图像(图像在服务器端上传文件夹和angularjs在不同的服务器上工作)?

我使用multer,node.js,mongodb上传图像。

我上载的文件夹中的图像,我存储在MongoDB中的path。

这是我的文件夹结构

在这里输入图像说明

服务器正在运行

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度服务器工作在不同的服务器节点服务器在不同的服务器上工作

我就这样

 </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中获取图像path,并返回图像的字节数组。

 // 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) }); }); 

将此字节数组绑定到您的标记。

  <img ng-src="{{'data:image/png;charset=utf-8;base64,' + response.data.path}}"> 

只需使用ng-src将path分配给图像即可

假设这是json的响应

 $scope.response = {"_id":"590051dcc90cf702e452b9c1","path":"uploads\login.jpg","name":"asdf","email":"asdf@gmail.com","originalname":"login.jpg","__v":0} 

在图片标签。

 <img ng-src"{{response.path}}"> 

您可以使用<img ng-src="{{response.path}}"/>

您可以确认图片是否可用在url“ http:// localhost:3000 / uploads / login.jpg ”?

如果不是,则图像path不正确。 请检查是否正确上传到文件夹。