【问题标题】:Serving image with ExpressJS and displaying it in DOM's img tag with Angular JS使用 ExpressJS 提供图像并使用 Angular JS 在 DOM 的 img 标签中显示它
【发布时间】:2016-05-30 04:56:49
【问题描述】:

我想以私密的方式使用 ExpressJS 提供图像。我认为通过静态服务它们是不可能的。因此,我会根据具有有效权限的请求为它们提供服务(请参阅下面的“validateTokens(req)”调用)。但是,当在我的 AngularJS 应用程序中接收它们时,我无法在 DOM 中显示。

这是我服务器的相关代码:

expressServer.get('/image', function (req, res){
    if (validateTokens(req)) {
        var filePath = path.join(__dirname, "./testImage.jpg");
        res.sendFile(filePath);
    }
});

这是我客户的相关代码:

var app = angular.module("app", []);
app.controller("indexController", function($http, $scope, $window){
    $http({
        method: 'GET',
        url: '/image'
    }).then(function successCallback(response) {
        var blob = new Blob([response.data], {type : 'image/jpeg'});
        $scope.imageData = $window.URL.createObjectURL(blob);
    }, function errorCallback(response) {
    });
});

这是我的 DOM 模板:

<!DOCTYPE html>
<html ng-app="app">
    <head>
        <meta charset="utf-8">
        <title>Node Testing</title>
        <script src="angular.min.js"></script>
        <script src="app.js"></script>
    </head>
    <body ng-controller="indexController as indexCtrl">
        <img data-ng-src="{{imageData}}" alt="Image to be shown" />
    </body>
</html>

【问题讨论】:

    标签: angularjs dom express


    【解决方案1】:

    您现在用于发送图像sendFile 的方法是用于下载目的。

    它设置所有必要的标题以强制浏览器开始下载。

    API Reference for sendFile

    您可以做的是在验证后发送一个 base64 编码的图像,该图像可以设置为图像的src 属性

    var fs = require("fs");
    fs.readFile("testimage.jpg", function(err, buffer){
        var base64Image = new Buffer(buffer, 'binary').toString('base64');
        res.send('data:image/jpeg;base64,' + base64Image);
    });
    

    然后从你的 Angular js 代码

    $http({
        method: 'GET',
        url: '/image'
    }).then(function successCallback(response) {
        $scope.imageData = response.data;
    }, function errorCallback(response) {
    });
    

    【讨论】:

    • 我需要解码响应还是什么?因为它仍然无法正常工作。
    • @JonathanGinsburg 更新了我的答案以连接到来自表达字符串'data:image/jpeg;base64,'的响应
    • 谢谢!解码对我有用,检查:stackoverflow.com/questions/16245767/….
    猜你喜欢
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    相关资源
    最近更新 更多