image.pngimage.pngimage.png

    1. //package.json
    2. {
    3. "name": "11.15-fileupload",
    4. "version": "1.0.0",
    5. "main": "index.js",
    6. "license": "MIT",
    7. "dependencies": {
    8. "koa": "^2.13.4",
    9. "koa-body": "^4.2.0",
    10. "koa-router": "^10.1.1",
    11. "koa-static": "^5.0.0"
    12. }
    13. }
    1. //add.html
    2. //引入外部样式
    3. <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
    4. <div class="container">
    5. <form action="http://localhost:5000/file" method="POST" role="form" enctype="multipart/form-data">
    6. <legend>添加小组成员</legend>
    7. <div class="form-group">
    8. <label for="">姓名</label>
    9. <input type="text" class="form-control" name="username" placeholder="name">
    10. </div>
    11. <div class="form-group">
    12. <label for="">年龄</label>
    13. <input type="text" class="form-control" name="age" placeholder="age">
    14. </div>
    15. <div class="form-group">
    16. <label for="">上传图像</label>
    17. <input type="file" class="form-control" name="logo" placeholder="Input field">
    18. </div>
    19. <button type="submit" class="btn btn-primary">添加数据</button>
    20. </form>
    21. </div>
    1. //index.js
    2. const koa = require("koa");
    3. const app = new koa();
    4. const router = require("koa-router")();
    5. const static = require("koa-static");
    6. const koaBody = require("koa-body");
    7. const path = require("path");
    8. const fs = require("fs");
    9. router.get("/",async ctx=>{
    10. ctx.body= "连接成功"
    11. })
    12. router.post("/file",async ctx=>{
    13. /* name,age */
    14. console.log(ctx.request.body)
    15. // console.log(ctx.request.files.logo.path)
    16. var logo = ctx.request.files.logo.path;
    17. /* 1、创建一个可读流 */
    18. var reader = fs.createReadStream(logo);
    19. /* 2、获取上传图片所在的路径和扩展名 */
    20. // console.log(path.basename(logo))
    21. var uploadFile = `./static/${path.basename(logo)}`;
    22. /* 3、创建一个可写流 */
    23. var writer = fs.createWriteStream(uploadFile);
    24. /* 4、将可读流通过管道写入可写流 */
    25. reader.pipe(writer);
    26. console.log(ctx.origin+"/"+path.basename(logo))
    27. ctx.body = "文件上传成功"
    28. })
    29. app.use(koaBody({
    30. multipart: true,
    31. formidable: {
    32. maxFileSize: 200 * 1024 * 1024,
    33. keepExtensions: true
    34. }
    35. }))
    36. app.use(router.routes());
    37. app.use(static(path.join(__dirname,"static")))
    38. app.listen(5000)