1.0.8 • Published 5 years ago
json-form-data-convertor v1.0.8
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.