koa2实现简单的图片上传

1、安装koa-body

2、引入koa-body 

const koa = require('koa');
const fs = require('fs');
const koaBody = require('koa-body');
const route = require('koa-route');
let app = new koa();

app.use(koaBody(
{
    multipart: true,
    formidable: {
        maxFileSize: 200*1024*1024   
    }
}));

3、上传文件的具体操作

const uploadFile = ctx => {
    const fileName = ctx.request.body.name;
    const file = ctx.request.files.file;
    // 创建可读流
    const render = fs.createReadStream(file.path);
    let filePath = path.join(config.BASE_PATH, 'upload/',fileName+'.'+file.name.split('.').pop());
    const fileDir = path.join(config.BASE_PATH, 'upload/');
    if (!fs.existsSync(fileDir)) {
      fs.mkdirSync(fileDir, err => {
        console.log(err)
        console.log('创建失败')
      });
    }
    // 创建写入流
    const upStream = fs.createWriteStream(filePath);
    render.pipe(upStream);
    ctx.body = '上传成功'
}

 4、前端ajax请求代码

<body>
    <div>
        <form>
            <input type="text" class="filename">
            <input type="file" name="file" class="imgPath">
            <div class="submitBtn">提交</div>
        </form>
    </div>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('.submitBtn').on('click',() => {
                var params = new FormData();
                params.append('name',$('.filename').val())
                params.append('file',$('.imgPath')[0].files[0])
                $.ajax({
                    data: params,
                    url: '/uploadFile',
                    type: 'post',
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        console.log(res)
                    }
                })
            })
        })
    </script>
    
</body>

 

posted @ 2019-04-23 18:10  Nicederen  阅读(4866)  评论(0编辑  收藏  举报