node.js - 如何将 base64 编码的内存图像作为文件参数发布

标签 node.js encoding base64

我有一个编码为 base64 字符串的图像,我正在尝试将其POST 作为另一个 REST API ( http://ocrapiservice.com/documentation/) 的参数。

我不想将文件存储在磁盘上 - 我想将文件保存在内存中,因为最终我想在客户端使用 getUserMedia 创建图像,我很可能使用不允许直接文件 IO 的托管服务。

我遇到的问题是,大多数示例我都可以使用 fs.createReadStream(somePath); 从磁盘中找到帖子图像,例如 https://github.com/mikeal/request/blob/master/README.md#forms

我更喜欢使用像 request 这样的库库,但也许这是不可能的。

我现在的代码是:

var fs = require( 'fs' );
var path = require( 'path' );

var request = require( 'request' );
var WS_URL = 'http://api.ocrapiservice.com/1.0/rest/ocr';

function ocr( postData ) {
    var r = request.post(WS_URL, completed);
    var form = r.form();

    form.append('apikey', 'REMOVED');
    form.append('language', 'en' );
    form.append('image', postData );

    function completed(error, response, body) {
        console.log( body );
    }
}

// This works
ocr( fs.createReadStream(path.join(__dirname, 'example.png' ) ) );

// This does not work
// ignore that it's being read from a file (the next line)
var base64Str = fs.readFileSync( 'example.png' ).toString('base64'); 

var buffer = new Buffer(base64Str, 'base64');
ocr( buffer.toString( 'binary' ) );

form.append 确实允许发送额外的参数,因此如果需要设置额外的 header ,那么这是可能的。

是否有某种类型的 Stream 包装器可供我使用?我试过使用这个 StringReader示例,并且可以修改它以至少发送文件名和正确的内容类型。

如何将内存中的文件作为参数发送到 Web 服务?

更新:

我已经修复/更新了上面的代码。

我从上面列出的 REST API 得到的响应是:

HTTP/1.1 400 Bad Request

No file provided

这是我正在运行的实际代码: https://gist.github.com/leggetter/4968764

最佳答案

在流版本中,您使用的是文件片段,但在 base64Image 版本中,您使用的是 base64 字符串。由于流版本有效,ocr API 显然希望表单只包含二进制数据,因此您需要在发送之前解码 base64 数据。

// Reading straight from a Buffer.
var imageData = fs.readFileSync('example.png');
ocr( imageData );

// Reading from a new Buffer created from a base64 string.
var base64Image = '...';
ocr(new Buffer(base64Image, 'base64'));

另请注意,在您的示例代码中:

// This line:
var base64Image = new Buffer(imageData, 'binary').toString('base64');

// does the same thing as this, because 'imageData' is alreadya  Buffer
var base64Image = imageData.toString('base64');

关于node.js - 如何将 base64 编码的内存图像作为文件参数发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14911746/

相关文章:

javascript - 序列化查询 : How to find column, "where:"列值不等于数组中的任何值

javascript - 使用node.js将url转发到游戏服务器

ruby - 使用 JSON.parse 时出现意外编码错误

mysql - ENOENT 与nodejs mysql 和sequelize

javascript - 在 Node.js res.redirect() 中包含 JSON

java - 使用 base 40 编码字符串有什么含义?

php - 相同字符串的 base64_encode() 值是否不同?

php - 字符串是 base 64 编码的吗?

使用 UTF8 编码将 Excel 转换为 CSV

php - XML-RPC 调用中奇怪的编码问题