To read more articles in this series please visit myMaking a blog, sample code please visithere.

multiparty

The previous section covered the complete file upload process, but in practice it would be impossible to develop all the functionality from scratch, which would be inefficient.

We can try to use a third-party library for POST request processing, such as Multiparty.

multiparty demo

You can test multiparty’s capabilities with the following example.

It returns the field name and value of the data information in the field event. In the file event, the field name and information for the file are returned.

After the success of the upload, will create an upload files in the specified folder, and files will be renamed (such as: IqUHkFe0u2h2TsiBztjKxoBR. JPG), in order to prevent the same name.

If the upload fails, the saved files will be automatically deleted.

The close event indicates that the form data has been fully parsed and the user can process the received information in it.

Example code: /lesson17/server.js

const http = require('http')
const multiparty = require('multiparty')

const server = http.createServer((req, res) => {
  const form = new multiparty.Form({
    uploadDir: './upload'}) form.parse(req) // Pass in the request parameters, and multiparty will process form.on('field', (name, value) => {console.log(name, value)}) form.on('file', (name, file, ... Rest) => {// File event console.log(name, file)}) form.on('close', () => {// Close event console.log()'Form data parsing completed')
  })
})

server.listen(8080)
Copy the code