100-days-Coding - day8

day8-0808

form表单同时上传文件和数据




    
    
    
    form


    
文件大小限制在1MB!

Koa作为sever

const Koa = require('koa');
const os = require('os');
const path = require('path');
const koaBody = require('koa-body');
const app = new Koa();

const main = async function (ctx) {
    console.log(ctx.request.body)
    const tmpdir = os.tmpdir();
    const filePaths = [];
    const files = ctx.request.body.files || {};
    console.log(files)

    for (let key in files) {
        const file = files[key];
        const filePath = path.join(tmpdir, file.name);
        const reader = fs.createReadStream(file.path);
        const writer = fs.createWriteStream(filePath);
        reader.pipe(writer);
        filePaths.push(filePath);
        filePaths.push(files[key])
    }

    ctx.body = filePaths;
};

app.use(koaBody({ multipart: true }));
app.use(main)

app.listen(3006, () => {
    console.log('server running ...')
})

未完待续......

你可能感兴趣的:(100-days-Coding - day8)