zoukankan      html  css  js  c++  java
  • nodejs上传多个文件

    以下方式皆用formidable: https://www.npmjs.com/package/formidable

    一、方式1

    文件一个一个的转存

    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) => {});
    })
    

    二、方式2

    解析出所有参数与文件后,一起转存

    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);
                }
            })
    })
    
  • 相关阅读:
    IHttpHandler and HttpModule
    sql page reship
    prototype
    google search engine theory
    ghost
    sql split
    Missing you is a kind of my deeppain in my life
    file control
    a story of c#(reship)
    teacher and student(reship)
  • 原文地址:https://www.cnblogs.com/Mr-Kahn/p/12177367.html
Copyright © 2011-2022 走看看