1-1 使用art-template配置html页面

  1. yarn add art-template koa-art-template
  2. yarn add koa koa-router koa2-cors
  3. //1.配置了art-template的模板引擎
  4. //2.配置了路由,跨域,post解析
  1. ##Tips:一定要给form表单加上enctype="multipart/form-data" ,才可以实现图片上传。
  2. <form action="" method="POST" role="form" enctype="multipart/form-data">
  3. <legend>图片上传</legend>
  4. <div class="form-group">
  5. <label for="">电影的名字</label>
  6. <input type="text" name="name" class="form-control" id="" placeholder="请输入电影的名字">
  7. </div>
  8. <div class="form-group">
  9. <label for="">评分</label>
  10. <input type="text" name="rating" class="form-control" id="" placeholder="评分">
  11. </div>
  12. <div class="form-group">
  13. <label for="">上传图片</label>
  14. <input type="file" name="file">
  15. </div>
  16. <button type="submit" class="btn btn-primary">Submit</button>
  17. </form>

1-2 koa-multer实现图片上传

  1. yarn add koa-multer
  1. const router = require("koa-router")();
  2. const multer = require('koa-multer')
  3. const storage = multer.diskStorage({
  4. // 图片位置
  5. destination: function (req, file, cb) {
  6. cb(null, `${process.cwd()}/static`)
  7. },
  8. filename: function (req, file, cb) {
  9. let type = file.originalname.split('.')[1]
  10. cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`)
  11. }
  12. })
  13. //加载配置
  14. var upload = multer({
  15. storage: storage
  16. });
  17. router.get("/",async ctx=>{
  18. await ctx.render("index")
  19. })
  20. router.post('/doUpload',upload.single('file'), async (ctx, next) => {
  21. console.log(ctx.req.body);
  22. console.log(ctx.req.file.filename)
  23. })
  24. module.exports = router;

1-3 连接数据库

  1. const mongoose = require("mongoose");
  2. /* 1.连接本地数据库 */
  3. mongoose.connect('mongodb://127.0.0.1:27017/movies', {
  4. useNewUrlParser: true
  5. });
  6. /* 2.在本地定义一个Schema和远程的数据库的字段映射 */
  7. var ImagesSchema = new mongoose.Schema({
  8. name: String,
  9. rating:String,
  10. imageUrl:String
  11. }, {
  12. versionKey: false // You should be aware of the outcome after set to false
  13. });
  14. /* 3.创建数据模型,和数据库中的表映射,获取表 */
  15. /* Top250Model 是我们获取的top250那张表 */
  16. var ImagesModel = mongoose.model("images",ImagesSchema)
  17. module.exports = ImagesModel;

1-4 存储数据

  1. router.post('/doUpload',upload.single('file'), async (ctx, next) => {
  2. var {name,rating} = ctx.req.body;
  3. var imageUrl = ctx.req.file.filename;
  4. var data = new ImagesModel({name,rating,imageUrl});
  5. data.save(err=>{
  6. if(err){throw err};
  7. })
  8. })

1-5 展示数据

  1. router.get("/show",async ctx=>{
  2. /* 查询数据 */
  3. var data = await ImagesModel.find({});
  4. await ctx.render("show",{arr:data})
  5. })
  1. //views/show.html
  2. {{each arr}}
  3. <p>{{$index}}-{{$value.name}}</p>
  4. <img src="{{$value.imageUrl}}" alt="">
  5. {{/each}}