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

How to display image in angular(image uploded in server side uploads folder and angularjs is working in different server)?

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

我是这样写的

</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 文件位于服务器端

只需使用 ng-src

分配图像的路径

假设这是响应 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}}"/>

在 Node JS 服务器上转换 get api 方法以从 Mongo Db 和 return 图像的字节数组中获取图像路径。

// 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}}">

能否请您确认图像是否在 url、“http://localhost:3000/uploads/login.jpg”中可用?

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