In the browser, we use the
application/x-www-form-urlencoded
: The default encoding type of the formmultipart/form-data
: If files are included, this type can only be selectedtext/plain
: Sends directly without encoding
The most important type is multipart/form-data, because files can be transferred. I’ve written about the underlying principle. In Node. js we usually use the form-data package to simulate forms in the browser as follows:
var form = new FormData()
form.append('my_string'.'my value')
form.append('my_integer'.1)
form.append('my_boolean'.true)
form.append('my_buffer', Buffer.from('hello'))
form.append('my_file', fs.readFileSync('/foo/bar.jpg'))
form.append('my_file', fs.createReadStream('/foo/bar.jpg'))
Copy the code
For file types, use either createReadStream or readFileSync to read the file. Here’s a point: Form-data handles these two formats differently. Take a look at the following two codes:
-
createReadStream
var media = new FormData() media.append('contentType'.'image/jpeg') media.append('value', fs.createReadStream('/Users/keliq/Pictures/1.jpeg')) Copy the code
-
readFileSync
var media = new FormData() media.append('contentType'.'image/jpeg') media.append('value', fs.readFileSync('/Users/keliq/Pictures/1.jpeg')) Copy the code
The result of packet capture is:
-
createReadStream
----------------------------015517802272525417891317 Content-Disposition: form-data; name="contentType" image/jpeg ----------------------------015517802272525417891317 Content-Disposition: form-data; name="value"; filename="1.jpeg" Content-Type: image/jpeg Copy the code
-
readFileSync
----------------------------152374567568773937407488 Content-Disposition: form-data; name="contentType" image/jpeg ----------------------------152374567568773937407488 Content-Disposition: form-data; name="value" Content-Type: application/octet-stream Copy the code
Content-type = application/octet-stream; content-type = application/octet-stream; content-type = application/octet-stream
var media = new FormData()
media.append('contentType'.'image/jpeg')
media.append('value', fs.readFileSync('/Users/keliq/Pictures/1.jpeg'), '1.jpeg')
Copy the code
This is the API provided by the form-data library:
// Set filename by providing a string for options
form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' );
// provide an object.
form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg'.contentType: 'image/jpeg'.knownLength: 19806});Copy the code
Check the source code because if a file name is provided, the lookup method of mime-types will automatically determine the content-Type, for example:
mime.lookup('json') // 'application/json'
mime.lookup('.md') // 'text/markdown'
mime.lookup('file.html') // 'text/html'
mime.lookup('folder/file.js') // 'application/javascript'
Copy the code
This is why content-Type changes from the default application/octet-stream to image/ JPEG when 1.jpeg is provided.