nodejs upload multiple files

The following are ways with formidable: https://www.npmjs.com/package/formidable

First, the way 1

A dump of a file

router.post(url, (req, res) => {
        let form = formidable.IncomingForm({
            encoding : 'utf-8',//上传编码
            uploadDir : temp_floder,//上传目录,指的是服务器的路径,如果不存在将会报错。
            keepExtensions : true,//保留后缀
            maxFieldsSize : 10 * 1024 * 1024//byte//最大可上传大小
        });
        let fields = {};        //formdata携带的参数信息
        form.on('field', (name, value) => {        //field事件会先file事件触发
            fields[name] = value;
        })
        .on('file', async (filename, file) => {
            // 可根据fields自由组合目录结构
            let resource_file_path = path.join(fields[index1], fields[index2], file.name);
            // 剪切文件,将带一串代码的文件,转存为正常命名与后缀的文件
            await moveFile(file.path, resource_file_path);
        })
        .on('end', () => {
            res.status(200).json({code: '1000', msg: '上传成功'});
        })
        .on('error', (err) => {
            res.status(400).json({code: '0000', msg: '上传失败'});
        })
        .parse(req, (err, fields, files) => {});
})

Second, the way 2

After parsing all the parameters with the file, along with dump

router.post(url, (req, res) =>{
        let form = formidable.IncomingForm({
            encoding : 'utf-8',//上传编码
            uploadDir : temp_floder,//上传目录,指的是服务器的路径,如果不存在将会报错。
            keepExtensions : true,//保留后缀
            maxFieldsSize : 10 * 1024 * 1024//byte//最大可上传大小
        });
        form.parse(req, async (err, fields, files) => {
            let resource_file_path;
            for(let file in files) {
                resource_file_path = path.join(fields[index1], fields[index2], file.name);
                // 剪切文件,将带一串代码的文件,转存为正常命名与后缀的文件
                await moveFile(file.path, resource_file_path);
            }
        })
})

Guess you like

Origin www.cnblogs.com/Mr-Kahn/p/12177367.html