Namespace: Forms:objectToFormData

Forms:objectToFormData

Source:

Methods

objectToFormData(formDataObject) → {FormData}

Constructs a FormData object, to be used in requests, from a given (plain) object, iterating its entries.

Additionally, this function streamlines field names, by discarding PHP-style array field name conventions like "files[]", by removing the brackets. So, if you have a field named "files[]" and another field named "files", both will just end up in one "files"-field.

Files and Blobs can be provided as-is (constructed programmatically of retrieved from file inputs via .files). Alternatively (and if you manually want to define the filename), you can provide plain objects to describe a File or Blob to add to the FormData:

  • use {file : File, ?name : String} to add "file" as a File and optionally set "name" to define a filename, taking precedence over what is already defined in the File object itself
  • use {blob : Blob|String, ?name : String, ?mimeType : String} to add "blob" as a Blob (if this is a string, it will be treated as the content of a new Blob), optionally using "name" as the filename (I'd recommend to set this) and optionally setting the file type via the MIME type defined in "mimeType".

In contrast to formDataToObject, this function does not need a polyfill in Internet Explorer, since it only uses the FormData constructor and the .append() method, which are both supported.

Parameters:
Name Type Description
formDataObject Object

object to iterate, to create FormData based on its entries

Source:
See:
Returns:
FormData object to be used in a request
Type
FormData
Example
const formData = objectToFormData({
  secrethash : 123456789,
	 firstname : 'Paul',
	 lastname : 'Atreides',
	 houses : ['Atreides', 'Fremen', 'Corrino'],
	 diary : {file : new File(['Dear Diary, ...'], 'diary.txt', {type : 'text/plain', lastModified : new Date()})},
	 instagramPage : {blob : '<html>...</html>', name : 'instagram.html', mimeType : 'text/html'},
}).getAll('houses');
=> ['Atreides', 'Fremen', 'Corrino']