1

How can I upload a string as a file, with an http post request using node.js?

Here is what I tried:

 var unirest = require('unirest');
    unirest.post('127.0.0.1/upload')
     .headers({'Content-Type': 'multipart/form-data'})
     .attach('file', 'test.txt', 'some text in file') // Attachment
    .end(function (response) {
       console.log(response.body);
    });

but nothing happens

J. Chomel
  • 8,193
  • 15
  • 41
  • 69
Stweet
  • 683
  • 3
  • 11
  • 26

1 Answers1

0

You must specify a file from the local file system. So I advise

  1. you create the file locally

    var fs = require('fs');
    fs.writeFile("/tmp/test", "some text in file", function(err) {
        if(err) { return console.log(err);  }
        console.log("The file was saved!");
    }); 
    
  2. send the file

    var unirest = require('unirest');
    unirest.post('127.0.0.1/upload')
        .headers({'Content-Type': 'multipart/form-data'})
        .attach('file', '/tmp/test') 
        .end(function (response) {
           console.log(response.body);
        });
    
J. Chomel
  • 8,193
  • 15
  • 41
  • 69