Created
October 6, 2014 16:29
-
-
Save alanhoff/847c90c857f29e3d0917 to your computer and use it in GitHub Desktop.
Enviar arquivo como anexo de um form-data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var fs = require('fs'); | |
| var path = require('path'); | |
| var os = require('os'); | |
| var cuid = require('cuid'); | |
| var request = require('request'); | |
| var Bluebird = require('bluebird'); | |
| Bluebird.resolve().then(function(){ | |
| console.log('Baixando captcha.'); | |
| var promise = Bluebird.pending(); | |
| var captcha = path.join(os.tmpdir(), cuid()); | |
| var writeStream = fs.createWriteStream(captcha); | |
| writeStream.on('finish', function(){ | |
| promise.resolve(captcha); | |
| }); | |
| request.get({ | |
| url: 'https://portaldocidadao.saude.gov.br/portalcidadao/captcha.png', | |
| strictSSL: false | |
| }).pipe(writeStream); | |
| return promise.promise; | |
| }).then(function(captcha){ | |
| console.log('Enviando formulário'); | |
| var promise = Bluebird.pending(); | |
| var form = request.post('http://httpbin.org/post', function(err, res, body){ | |
| if(err) | |
| return promise.reject(err); | |
| promise.resolve(body); | |
| }).form(); | |
| form.append('captcha', fs.createReadStream(captcha),{ | |
| filename: 'captcha.png', | |
| contentType: 'image/png' | |
| }); | |
| return promise.promise; | |
| }).then(function(body){ | |
| var json = JSON.parse(body); | |
| console.log(json); | |
| }).catch(function(err){ | |
| console.log('Ocorreu um erro.'); | |
| console.log(err.stack); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment