ThoughtWork

100-days-Coding - day8

2018-08-08  本文已影响2人  亨利何

day8-0808

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>form</title>
</head>
<body>
    <div id="content">
        <form id="uploadForm" action="http://localhost:3006" method="POST">
            <input type="file" name="file" id="input-file" value="选择你要提交的文件""><span>文件大小限制在1MB!</span> 

            <input type="text" name="namefield" id="input-name" value="666" style="display: none;">
            <input type="submit" value="提交"" id="btn-submit">
        </form>
    </div>

    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>

        // ajax form submit
        var upload_form = $("#uploadForm")
        upload_form.submit(function () {
            var form_data = new FormData()
            form_data.append('ID', $('#input-name').val())
            form_data.append('file',$('#input-file')[0].files[0])

            console.log(form_data)
            console.log($('#input-file')[0].files[0])

            $.ajax({
                url: 'http://localhost:3006',
                type: 'post',
                data: form_data,
                cache: false,
                processData: false,
                contentType: false,
                success: function (res) {},
                error: function (e) {}
            })
        })
    </script>
</body>
</html>

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 ...')
})

未完待续......

上一篇下一篇

猜你喜欢

热点阅读