将图像内容而非图像路径存储在mongodb中

Store image content not image path in mongodb

本文关键字:图像 存储 路径 mongodb      更新时间:2024-05-02

我现在已经看到了许多问题和解决方案。我是MongoDB和MEAN堆栈开发的新手。我想知道是否有存储图像内容本身,而不是MongoDB中图像文件的路径。所有的解决方案都建议将图像存储为缓冲区,然后通过将缓冲区转换为base64在源中使用它。我这样做了,但结果输出解析为图像文件的路径,而不是图像内容。我希望将图像本身保存在数据库中。

// saving image
var pic = {name : "profilePicture.png",
           img : "images/default-profile-pic.png",
           contentType : "image/png"
           };
//schema
profilePic:{ name: String, img: Buffer, contentType: String }
//retrieving back
var base64 = "";
var bytes = new Uint8Array( profilePic.img.data );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
    base64 += String.fromCharCode( bytes[ i ] );
}
var proPic = "data:image/png;base64," + base64;
console.log(proPic);
//console output
data:image/png;base64,images/default-profile-pic.png

proPic的输出解析为"data:image/png;base64,images/default profile pic.png"

我在发布这个之前提到的几个链接

如何在node.js中进行Base64编码?

如何使用javascript 将图像转换为base64字符串

问题很简单,你没有读取和编码图片。相反,您使用路径作为字符串。

使用节点的服务器端

如果您想在服务器端使用文件系统上的映像执行它,您可以使用以下内容:

var fs = require('fs');
// read and convert the file
var bitmap = fs.readFileSync("images/default-profile-pic.png");
var encImage = new Buffer(bitmap).toString('base64');
// saving image
var pic = {name : "profilePicture.png",
           img : encImage,
           contentType : "image/png"
           };
....

客户端

同样,我们需要加载图像并将其编码为base64。这里有一个关于在客户端上执行此操作的答案。

使用第一种方法,结果如下:

function toDataUrl(url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}
toDataUrl("images/default-profile-pic.png", function(encImage){
    // saving image
    var pic = {name : "profilePicture.png",
               img : encImage,
               contentType : "image/png"
               };
    //Proceed in the callback or use a method to pull out the data
    .... 
});

下面的两个链接节省了我的时间。如果我们使用"ng文件上传",我们的生活从此变得轻松。

https://github.com/danialfarid/ng-file-upload#install

https://github.com/danialfarid/ng-file-upload

以下是对我有效的

//my html code
<div>
     <button type="file" ngf-select="onFileSelect($file)" ng-model="file" name="file" ngf-pattern="'image/*'" 
     ngf-accept="'image/*'" ngf-max-size="15MB" class="btn btn-danger">
     Edit Profile Picture</button>
</div>
//my js function
        function onFileSelect(file){
        //var image =  document.getElementById('uploadPic').files;
        image = file;
        if (image.type !== 'image/png' && image.type !== 'image/jpeg') {
            alert('Only PNG and JPEG are accepted.');
            return;
        }
        $scope.uploadInProgress = true;
        $scope.uploadProgress = 0;
        var reader = new window.FileReader();
        reader.readAsDataURL(image);
        reader.onloadend = function() {
            base64data = reader.result;
            $scope.profile.profilePic = base64data;
            ProfileService.updateProfile($scope.profile).then(function(response){
                $rootScope.profile = response;
                $scope.profilePicture = $rootScope.profile.profilePic;
            });
        }
    }
// when reading from the server just put the profile.profilePic value to src
src="data:image/png;base64,{base64 string}"
// profile schema
var ProfileSchema = new mongoose.Schema({
    userid:String,
    //profilePic:{ name: String, img: Buffer, contentType: String },
    profilePic:String
}

我不会说这是最好的解决方案,但这是一个很好的起点。此外,这限制了您上传超过16 MB的文件,在这种情况下,您可以在上面的实现中使用"GridFs",最初文件被转换为"blob",然后我将其转换为"base64"格式,并将其添加到我的配置文件的字符串变量中。

希望这能帮助人们节省时间。