保存到磁盘

时间:2015-05-30 01:11:41

标签: javascript angularjs node.js http

我将base64剪贴板映像发布到服务器(节点),我将base64保存到磁盘。由于某种原因,图像已损坏。

发布的客户端逻辑:

function sendData($http, clipboardImage) {
    // $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    // var imgData = JSON.stringify(clipboardImage);
    //var data = {"imgdata" : clipboardImage}; 
    var url = "http://localhost:3000/pad/img/";

    $http({
        method: 'POST',
        url: url,
        data: "data=" + clipboardImage
    });
}

$("[ng-model='html']").delegate("p", "paste", function(event) {
    var items = (event.clipboardData || event.originalEvent.clipboardData).items;
    console.log(JSON.stringify(items)); // will give you the mime types
    // find pasted image among pasted items
    var blob = null;
    for (var i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") === 0) {
            blob = items[i].getAsFile();
        }
    }
    // load image if there is a pasted image
    if (blob !== null) {
        var reader = new FileReader();
        reader.onload = function(e) {
            sendData($http, e.target.result);
        };
        reader.readAsDataURL(blob);
    }
});

服务器逻辑:

app.post("/pad/img/", function(req, res) {
    var imgB64Data = req.body.data;
    var decodedImg = decodeBase64Image(imgB64Data);
    var imageBuffer = decodedImg.data;
    var type = decodedImg.type;
    var extension = mime.extension(type);
    var fileName = "image." + extension;
    try {
        fs.writeFile(fileName, imageBuffer, function(err) {
            console.log(err);
        });
    } catch (err) {
        console.error(err);
    }
});

function decodeBase64Image(dataString) {
    var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
        response = {};

    if (matches.length !== 3) {
        return new Error('Invalid input string');
    }

    response.type = matches[1];
    response.data = new Buffer(matches[2], 'base64');

    return response;
}

图像正在成功保存,但似乎已损坏。你能指出可能遗漏的东西吗?

1 个答案:

答案 0 :(得分:0)

您是否尝试在调用fs.writeFile时明确设置文件编码?

try {
    fs.writeFile(fileName, imageBuffer, {encoding:'utf8'}, function(err) {
        console.log(err);
    });
} catch (err) {
    console.error(err);
}

NodeJS文档:fs.writeFile(filename, data\[, options\], callback)