Send a string as a file using request in Node

9

I have a String and I want to convert it to a stream to send it as if it were a file via multipart of request .

I want to do it in the air, without generating the file on disk.

I'm doing it this way:

const stream = require("stream")

module.exports = function () {
        let readStream = new stream.PassThrough()
        readStream.end(new Buffer('<file data>'), () => {

            const options = {
                url: '<url>',
                method: 'POST',
                json: true,
                formData: {
                    file: readStream
                }
            };
            request(options, (error, res)=> {
                if(error) {
                    console.log(JSON.stringify(error))
                }
            });
        })
    })
}

... and it returns the following error:

{
    "code":"BadRequestError",
    "message":"MultipartParser.end(): stream ended unexpectedly: state = PART_DATA"
}
    
asked by DaniGS 15.03.2017 в 17:54
source

2 answers

3

I can think of 2 ways:

No stream

  • Using formData of request we send the custom_file .

module.exports = function () {
  const options = {
      url: '<url>',
      method: 'POST',
      json: true,
      formData: {
        custom_file: {
          value: '<file data>',
          options: {
            filename: 'file.txt',
            contentType: 'text/plain'
          }
        }
      }
  };

  let req = request(options, (error, res)=> {
      if(error) {
          console.log(JSON.stringify(error))
      }
  })
}

With stream

  • Using Readable you create a stream of string .

Example:

const Readable = require('stream').Readable

module.exports = function () {

  //
  let stream = new Readable;
  stream._read = function noop() {};
  stream.push('<file data>');
  stream.push(null); // Indicamos fin del archivo (fin del stream)
  

  const options = {
      url: '<url>',
      method: 'POST',
      json: true,
      formData: {
        custom_file: {
          value: stream,
          options: {
            filename: 'file.txt',
            contentType: 'text/plain'
          }
        }
      }
  };
  
  let req = request(options, (error, res)=> {
      if(error) {
          console.log(JSON.stringify(error))
      }
  })
}
    
answered by 24.03.2017 / 18:41
source
0

Well what you need to do is change the MIME type in the header.

const options = {
    headers: {
        "Content-Disposition":"attachment; filename=\"{filename}\""
    }
    url: '<url>',
    method: 'POST',
    json: true,
    formData: {
        file: readStream
    }
};
    
answered by 29.03.2017 в 23:25