前端:
<template>
<div>
<input @change="uploadPhoto" type="file" />
<img :src="base64" style="width:100px;height:100px" />
</div>
</template>
<script>
export default {
data() {
return {
base64: ""
};
},
methods: {
uploadPhoto(e) {
let file = e.target.files[0];
let fileFormat = file.name.split(".");
let filename =
fileFormat[0] + Date.now() + "." + fileFormat[fileFormat.length - 1];
let filesize = file.size;
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = async e => {
let imgcode = e.target.result;
let {
data: { base64 }
} = await this.$axios.post("/api/test/uploadimg", {
filename: filename,
filesize: filesize,
base64: imgcode
});
this.base64 = base64;
console.log("图片上传成功!");
};
}
}
};
</script>
服务端routes/test.js
const router = require('koa-router')()
const TestModel = require('../model/test.js')
router.prefix('/test')
router.post('/uploadimg', async (ctx, next) => {
let {
filename,
filesize,
base64
} = ctx.request.body
const result = await TestModel.create({
filename: filename,
filesize: filesize,
base64: base64
})
if (result) {
let { filename, filesize, base64 } = result;
ctx.body = {
message: "成功!",
code: 1,
base64
}
} else {
ctx.body = {
message: "失败le "
}
console.log("失败了")
}
})
module.exports = router
model/test.js
const mongoose = require('../db.js')
let TestSchema = mongoose.Schema({
filename: { type: String },
filesize: { type: Number },
base64: { type: String }
})
// 创建模型对象
// 第一个参数与集合对应,第二个对象指定约束对象实例
module.exports = mongoose.model('Test', TestSchema, "test")