[英]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}
我將以上響應發送給有角和無序的應用程序。
現在我想以角度顯示此圖像。
角度服務器在其他服務器中工作節點服務器在其他服務器中工作
我這樣放
</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)
});
});
將此字節數組綁定到標簽。
<img ng-src="{{'data:image/png;charset=utf-8;base64,' + response.data.path}}">
只需使用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}}"/>
您能否確認圖片在url'http:// localhost:3000 / uploads / login.jpg '中是否可用 ?
如果不正確,則圖像路徑不正確。 請檢查它是否正確上傳到文件夾中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.