I have an image encoded as a base64 String and I'm trying to POST
it as a parameter to another REST API (http://ocrapiservice.com/documentation/).
I don't want to have to store the file on disk - I want to keep the file in memory because eventually I want to create the image using getUserMedia
on the client and I'll likely use a hosted service that doesn't allow direct file IO.
The problem I have is that most examples I can find post images from disk using fs.createReadStream(somePath);
e.g.
https://github.com/mikeal/request/blob/master/README.md#forms
I'd prefer to use a library such as the request library but maybe that won't be possible.
The code I have right now is:
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
does allow additional parameter to be sent so if additional headers need to be set then that is possible.
Is there a Stream
wrapper of some kind that I can use? I've tried using this StringReader example and it is possible to modify it to at least send a filename and the correct Content-Type.
How do I achieve this posting of an in memory file as a parameter to a web service?
Update:
I've fixed/updated the code above.
The response I get from the REST API listed above is:
HTTP/1.1 400 Bad Request
No file provided
Here's the actual code that I'm running: https://gist.github.com/leggetter/4968764