1.0.8 • Published 5 years ago

json-form-data-convertor v1.0.8

Weekly downloads
1
License
ISC
Repository
-
Last release
5 years ago

Json-Form-Data-Convertor

A library to generate form multipart/form-data body from a javascript object. Can be used to submit forms and file uploads to other endpoints.

Install

npm install --save json-form-data-convertor

Usage

In this example we are constructing a form with 2 fields that contain a string, and a file stream and posting it to an url using node-fetch library.

const jsonFormData = require('json-form-data-convertor');
const testEndpoint = 'http://localhost:3000';
const fetch = require('node-fetch');

var jsonForm = {
  name: 'test',
  @file: {
      path: './test.txt',
      filename: 'text.txt'
  }
}

var formData  = jsonFormData.convert(form);
var result = await fetch(testEndpoint, {
  method: 'POST',
  body: formData
}).catch((err) => {
  console.log(err);
});

Also you can pass array of files stream in a single attribute :

const jsonFormData = require('json-form-data-convertor');
const testEndpoint = 'http://localhost:3000';
const fetch = require('node-fetch');

var jsonForm = {
  name: 'test',
  @files: [{
      path: './test.txt',
      filename: 'text.txt'
  }, {
      path: './test2.txt',
      filename: 'text2.txt'
  }]
}

var formData  = jsonFormData.convert(form);
var result = await fetch(testEndpoint, {
  method: 'POST',
  body: formData
}).catch((err) => {
  console.log(err);
});

Methods

FormData generate( Mixed object)

Generate form data from the json object.

var formData = jsonFormData.convert({
  name: 'test',
  @file: {
      path: './test.txt',
      filename: 'text.txt'
  }
});

Note

As shown in the example above, file stream attributes are handled by prefixing their name with '@' character and using the following specific syntax

{
  path:{{file_path}},
  filename: {{file_name}}
}

License

Json-Form-Data-Convertor is released under the MIT license.

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago