1-1 使用art-template配置html页面
yarn add art-template koa-art-template
yarn add koa koa-router koa2-cors
//1.配置了art-template的模板引擎
//2.配置了路由,跨域,post解析
##Tips:一定要给form表单加上enctype="multipart/form-data" ,才可以实现图片上传。
<form action="" method="POST" role="form" enctype="multipart/form-data">
<legend>图片上传</legend>
<div class="form-group">
<label for="">电影的名字</label>
<input type="text" name="name" class="form-control" id="" placeholder="请输入电影的名字">
</div>
<div class="form-group">
<label for="">评分</label>
<input type="text" name="rating" class="form-control" id="" placeholder="评分">
</div>
<div class="form-group">
<label for="">上传图片</label>
<input type="file" name="file">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
1-2 koa-multer实现图片上传
yarn add koa-multer
const router = require("koa-router")();
const multer = require('koa-multer')
const storage = multer.diskStorage({
// 图片位置
destination: function (req, file, cb) {
cb(null, `${process.cwd()}/static`)
},
filename: function (req, file, cb) {
let type = file.originalname.split('.')[1]
cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`)
}
})
//加载配置
var upload = multer({
storage: storage
});
router.get("/",async ctx=>{
await ctx.render("index")
})
router.post('/doUpload',upload.single('file'), async (ctx, next) => {
console.log(ctx.req.body);
console.log(ctx.req.file.filename)
})
module.exports = router;
1-3 连接数据库
const mongoose = require("mongoose");
/* 1.连接本地数据库 */
mongoose.connect('mongodb://127.0.0.1:27017/movies', {
useNewUrlParser: true
});
/* 2.在本地定义一个Schema和远程的数据库的字段映射 */
var ImagesSchema = new mongoose.Schema({
name: String,
rating:String,
imageUrl:String
}, {
versionKey: false // You should be aware of the outcome after set to false
});
/* 3.创建数据模型,和数据库中的表映射,获取表 */
/* Top250Model 是我们获取的top250那张表 */
var ImagesModel = mongoose.model("images",ImagesSchema)
module.exports = ImagesModel;
1-4 存储数据
router.post('/doUpload',upload.single('file'), async (ctx, next) => {
var {name,rating} = ctx.req.body;
var imageUrl = ctx.req.file.filename;
var data = new ImagesModel({name,rating,imageUrl});
data.save(err=>{
if(err){throw err};
})
})
1-5 展示数据
router.get("/show",async ctx=>{
/* 查询数据 */
var data = await ImagesModel.find({});
await ctx.render("show",{arr:data})
})
//views/show.html
{{each arr}}
<p>{{$index}}-{{$value.name}}</p>
<img src="{{$value.imageUrl}}" alt="">
{{/each}}