Foreword before want to do a accept file save to the local node service, searched through the whole network most are shallow tasted, point so far. Paste two pieces of code and you’re done. After a period of time to explore to write a complete usable service, I hope to provide some ideas for the development of relevant needs.

The effect

Our front-end file transfer usually adopts formData format, so the core of the server side lies in how to parse formData format data. At present, the popular parsing plug-ins mainly include Multiparty and Busboy, but I have seen that most of the data are around multiparty. So I also use multiparty for data parsing.

Multiparty official documentation

Before introducing plug-ins

npm install multiparty
Copy the code

After that, the easiest way is to pass the path of the file to the plug-in directly, which can be automatically parsed and saved (note that the file path must exist otherwise an error will be reported).

(req, res)=>{
var form = new multiparty.Form({uploadDir:'Save file address'})
// Parse
form.parse(req)
}

Copy the code

But this method plug-in saves files to memory and then from memory to disk, we can directly create a stream to write data to disk.

Listening for Part events

Emitted when a part is encountered in the request. part is a ReadableStream. It also has the following propertie

Gets a file readable stream, then creates a write stream based on the file path, and then writes the file stream.

The complete code

const express = require('express');
const multiparty = require('multiparty');
const app = express();
const fs = require('fs');
const path = require('path')
const Busboy = require('busboy');

app.get('/'.(req, res) = > {
    res.send('hello, this is a node server for upload file current env is' + process.env.NODE_ENV)
})
/ / across domains
app.use(function (req, res, next) {
    if (req.method == 'OPTIONS') res.send('OPTIONS PASS')
    res.append('Access-Control-Allow-Origin'.The '*')
    res.append('Access-Control-Allow-Methods'.'OPTIONS, GET, PUT, POST, DELETE')
    res.append('Access-Control-Allow-Headers'.The '*')
    next();
});
/ / upload
app.post('/upload'.(req, res) = > {
    const form = new multiparty.Form();
    try {
        form.on('part'.async function (part) {
            if (part.filename) {
                // Get the upload path
                const p = await new Promise((resolve, reject) = > {
                    form.on('field'.(name, value) = > {
                        resolve(name == 'path'? value:' ')})})const saveTo = (process.env.NODE_ENV == 'dev' ? 'D://Temp' : '/usr/static') + (p || '/default')
                // Create a folder if no folder path exists
                await new Promise((resolve, reject) = > {
                    fs.stat(saveTo, (err) = > {
                        if (err) {
                            fs.mkdirSync(saveTo);
                        }
                        resolve()
                    })
                })
                // Create a write stream based on the path
                const writeStrem = fs.createWriteStream(path.join(saveTo, part.filename))
                part.pipe(writeStrem)
            }
            part.on('error'.function (err) {
                fileStrem.destroy();
            });
        });
        form.parse(req)
    } catch (e) {
        console.log(e)
        res.send('500')
    }
    res.send('200')
})
app.listen(8010.function () {
    console.log('Example app listening on port 8010! \n');
});
Copy the code

Busboy also writes to the file stream

const express = require('express');
const multiparty = require('multiparty');
const app = express();
const fs = require('fs');
const path = require('path')
const Busboy = require('busboy');

app.get('/'.(req, res) = > {
    res.send('hello, this is a node server for upload file current env is' + process.env.NODE_ENV)
})
/ / across domains
app.use(function (req, res, next) {
    if (req.method == 'OPTIONS') res.send('OPTIONS PASS')
    res.append('Access-Control-Allow-Origin'.The '*')
    res.append('Access-Control-Allow-Methods'.'OPTIONS, GET, PUT, POST, DELETE')
    res.append('Access-Control-Allow-Headers'.The '*')
    next();
});
/ / upload
app.post('/upload'.(req, res) = > {
    // const form = new multiparty.Form();
    // try {
    // form.on('part', async function (part) {
    // if (part.filename) {
    // // Obtain the upload path
    // const p = await new Promise((resolve, reject) => {
    // form.on('field', (name, value) => {
    // resolve(name == 'path'? value:'')
    / /})
    / /})
    // const saveTo = (process.env.NODE_ENV == 'dev' ? 'D://Temp' : '/usr/static') + (p || '/default')
    // // Create a folder if no folder path exists
    // await new Promise((resolve, reject) => {
    // fs.stat(saveTo, (err) => {
    // if (err) {
    // fs.mkdirSync(saveTo);
    / /}
    // resolve()
    / /})
    / /})
    // // Creates a write flow based on the path
    // const writeStrem = fs.createWriteStream(path.join(saveTo, part.filename))
    // part.pipe(writeStrem)
    / /}
    // part.on('error', function (err) {
    // fileStrem.destroy();
    / /});
    / /});
    // form.parse(req)
    // } catch (e) {
    // console.log(e)
    // res.send('500')
    // }
    const busboy = new Busboy({ headers: req.headers });
    busboy.on('file'.function(fieldname, file, filename, encoding, mimetype) {
        var saveTo = path.join('D://Temp', path.basename(filename));
        file.pipe(fs.createWriteStream(saveTo));
      });
      busboy.on('finish'.function() {
        res.writeHead(200, { 'Connection': 'close' });
        res.end("That's all folks!");
      });
      return req.pipe(busboy); 
})
app.listen(8010.function () {
    console.log('Example app listening on port 8010! \n');
});
Copy the code