strict-form-data

1.0.1 • Public • Published

说明

2017.3.9更新,新增data内容体不加boundary的选项,为了应对腾讯云的上传文件接口会把文件头尾的东西也写进去,腾讯云不处理这个东西:

----------------------------089247522215702630087052
Content-Disposition: form-data; name="data"; filename="upload.md"
Content-Type: text/x-markdown

所以需要我们去处理,像下面这样使用即可去掉这些

const formRequest = new FormData({
    includeBoundary:false //false表示在写data的时候不用写入头尾的那一坨
});

fork自form-data,主要改了一下form-data设置的请求头,原作者请求头里的Content-Type写死为content-type,这里有部分业务后端接口确实不支持这个为小写,问过原作者了也说新的http协议说要小写,不予支持..而本人又说服不了后端,只能fork出来发个 兼容的版本。sad.

改了下面的:

FormData.prototype.getHeaders = function(userHeaders) {
  var header;
  var formHeaders = {
    'Content-Type': 'multipart/form-data; boundary=' + this.getBoundary()
  };

  for (header in userHeaders) {
    if (userHeaders.hasOwnProperty(header)) {
      formHeaders[header.toLowerCase()] = userHeaders[header];
    }
  }

  return formHeaders;
};

Form-Data NPM Module Join the chat at https://gitter.im/form-data/form-data

A library to create readable "multipart/form-data" streams. Can be used to submit forms and file uploads to other web applications.

The API of this library is inspired by the XMLHttpRequest-2 FormData Interface.

Linux Build MacOS Build Windows Build

Coverage Status Dependency Status bitHound Overall Score

Install

npm install --save form-data

Usage

In this example we are constructing a form with 3 fields that contain a string, a buffer and a file stream.

var FormData = require('form-data');
var fs = require('fs');
 
var form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));

Also you can use http-response stream:

var FormData = require('form-data');
var http = require('http');
 
var form = new FormData();
 
http.request('http://nodejs.org/images/logo.png', function(response) {
  form.append('my_field', 'my value');
  form.append('my_buffer', new Buffer(10));
  form.append('my_logo', response);
});

Or @mikeal's request stream:

var FormData = require('form-data');
var request = require('request');
 
var form = new FormData();
 
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', request('http://nodejs.org/images/logo.png'));

In order to submit this form to a web application, call submit(url, [callback]) method:

form.submit('http://example.org/', function(err, res) {
  // res – response object (http.IncomingMessage)  //
  res.resume();
});
 

For more advanced request manipulations submit() method returns http.ClientRequest object, or you can choose from one of the alternative submission methods.

Alternative submission methods

You can use node's http client interface:

var http = require('http');
 
var request = http.request({
  method: 'post',
  host: 'example.org',
  path: '/upload',
  headers: form.getHeaders()
});
 
form.pipe(request);
 
request.on('response', function(res) {
  console.log(res.statusCode);
});

Or if you would prefer the 'Content-Length' header to be set for you:

form.submit('example.org/upload', function(err, res) {
  console.log(res.statusCode);
});

To use custom headers and pre-known length in parts:

var CRLF = '\r\n';
var form = new FormData();
 
var options = {
  header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,
  knownLength: 1
};
 
form.append('my_buffer', buffer, options);
 
form.submit('http://example.com/', function(err, res) {
  if (err) throw err;
  console.log('Done');
});

Form-Data can recognize and fetch all the required information from common types of streams (fs.readStream, http.response and mikeal's request), for some other types of streams you'd need to provide "file"-related information manually:

someModule.stream(function(err, stdout, stderr) {
  if (err) throw err;
 
  var form = new FormData();
 
  form.append('file', stdout, {
    filename: 'unicycle.jpg',
    contentType: 'image/jpg',
    knownLength: 19806
  });
 
  form.submit('http://example.com/', function(err, res) {
    if (err) throw err;
    console.log('Done');
  });
});

For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to form.submit() as first parameter:

form.submit({
  host: 'example.com',
  path: '/probably.php?extra=params',
  auth: 'username:password'
}, function(err, res) {
  console.log(res.statusCode);
});

In case you need to also send custom HTTP headers with the POST request, you can use the headers key in first parameter of form.submit():

form.submit({
  host: 'example.com',
  path: '/surelynot.php',
  headers: {'x-test-header': 'test-header-value'}
}, function(err, res) {
  console.log(res.statusCode);
});

Integration with other libraries

Request

Form submission using request:

var formData = {
  my_field: 'my_value',
  my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};
 
request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful!  Server responded with:', body);
});

For more details see request readme.

node-fetch

You can also submit a form using node-fetch:

var form = new FormData();
 
form.append('a', 1);
 
fetch('http://example.com', { method: 'POST', body: form })
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);
    });

Notes

  • getLengthSync() method DOESN'T calculate length for streams, use knownLength options as workaround.
  • Starting version 2.x FormData has dropped support for node@0.10.x.

License

Form-Data is released under the MIT license.

Readme

Keywords

none

Package Sidebar

Install

npm i strict-form-data

Weekly Downloads

0

Version

1.0.1

License

MIT

Last publish

Collaborators

  • xiaomingplus