使用koa2实现一个图片管理的web应用程序,可以完成图片的上传(多张图选择以及上传文件类型过滤)、图片列表的显示(显示图片以及图片原名称,数据条数较多时需要分页,每页10条)、从图片列表删除特定图片。
要求:
(1)需要自己设计数据库表结构,来完成对图片数据的存储、查询、删除的过程。
(2)需要有简易的页面完成对上述功能的展示。
(3)提交代码,以插入代码块方式提交核心实现代码。
(4)将整个项目以压缩包形式提交附件。
(5)录制实现效果展示视频,上传到第三方平台并提交视频地址
保证自己独立认真完成,该教学实践评分将作为期末考核不满60分一票否决成绩
const mysql = require('mysql2/promise');
const koa = require('koa');
const app = new koa();
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');//结构请求获取数据
const cors = require('koa2-cors');//跨域
const fs = require('fs')
const mime = require('mime-types')
var router = new Router();
app.use(bodyParser());
app.use(cors({ origin: '*', methods: 'GET,PUT,POST,DELETE' }));
const con = mysql.createPool({
host: '192.168.229.232',
port: 3306,
user: 'root',
password: '123123',
database: 'imgmanager'
});
router.get('/getImageData', async (ctx) => {
let [b] = await con.execute(`select id,name,path from image`);
ctx.body = b
})
router.post('/getImage', async (ctx, next) => {
let path = ctx.request.body.path
ctx.body = `data:${mime.lookup(path)};base64,` + fs.readFileSync(path, 'base64')
})
router.post('/uploadImage', async (ctx, next) => {
let data = ctx.request.body;
try {
data.forEach(async (e, index) => {
let path = `./image/${e.name}`
if (!fs.existsSync(path)) {
fs.writeFileSync(path, e.value.split(',')[1],'base64')
let [a] = await con.execute("INSERT INTO `imgmanager`.`image` (`name`,`path`) VALUES (?,?);", [e.name, path])
}
});
ctx.body = 'complete'
} catch (error) {
ctx.body = error
}
})
router.post('/deleteImageData', async (ctx) => {
try {
let data = ctx.request.body
let [e] = await con.execute(`delete from image where id = ?`, [data.id]);
console.log(data.path)
fs.unlinkSync(data.path)
ctx.body = 'complete'
} catch (error) {
ctx.body = error
}
})
async function aa(){
let [row] = await con.execute('select * from image')
console.log( row)
}
aa()
app.use(router.routes())
app.listen(8080)
import { Button, Upload, message, List} from 'antd';
import { UploadOutlined } from '@ant-design/icons'
import axios from 'axios';
import React, { useEffect, useState } from 'react';
function fileToBase64(element) {
return new Promise(function (res, rej) {
const fileReader = new FileReader()
if (element.originFileObj) {
fileReader.readAsDataURL(element.originFileObj);
} else {
fileReader.readAsDataURL(element);
}
fileReader.onload = function (element) {
let dataURL = element.target.result
res(dataURL)
}
})
}
function App() {
const [upLoadFile, setUpLoadFile] = useState([])
const [imageData, setImageData] = useState([])
const [imgUrl, setImgUrl] = useState([])
useEffect(() => {
axios.get('http://localhost:8080/getImageData')
.then((res) => {
setImageData(res.data)
console.log(res.data)
})
}, [])
const deleteImageData = (element) => {
axios.post('http://192.168.229.232:8080/deleteImageData', { id: element.id, path: element.path })
.then((result) => {
message.success('删除成功')
axios.get('http://192.168.229.232:8080/getImageData')
.then((res) => {
setImageData(res.data)
})
})
}
const getImageOnly = (element, index) => {
console.log(element)
axios.post('http://192.168.229.232:8080/getImage', { path: element.path })
.then((res) => {
console.log(res.data)
setImgUrl({ index: index, url: res.data })
})
}
const uploadImage = async () => {
let data = []
console.log(upLoadFile.length)
for (let i = 0; i < upLoadFile.length; i++) {
data.push({
name: upLoadFile[i].name,
value: await fileToBase64(upLoadFile[i])
})
}
axios.post('http://192.168.229.232:8080/uploadImage', data)
.then((result) => {
axios.get('http://192.168.229.232:8080/getImageData')
.then((res) => {
setImageData(res.data)
message.success('上传成功')
})
})
}
return (
<div>
<List
size="small"
bordered
dataSource={imageData}
pagination={{ defaultCurrent: 1, pageSize: 10, total: imageData.length }}
renderItem={(item, index) => {
return <List.Item>
<div>
文件名:<div style={{ fontSize: '150%' }}>{item.name.split('.')[0]}</div>
{' '}
路径:<div style={{ fontSize: '150%' }}>{item.path} {' '}</div>
<Button onClick={() => { deleteImageData(item) }}>删除</Button>
<Button onClick={() => { getImageOnly(item, index) }}>查看图片</Button>
{imgUrl.index == index ? <img width={'200px'} src={imgUrl.url} /> : <></>}
</div>
</List.Item>
}}
/>
<Upload
accept='.jpg,.png,.jpeg,.bpm'
listType="picture"
maxCount={3}
multiple
beforeUpload={(file, files) => {
console.log(files)
setUpLoadFile([...upLoadFile, ...files]);
return false;
}
}
>
<Button icon={<UploadOutlined />}>选择图片</Button>
</Upload>
<Button type='primary' onClick={() => {
uploadImage()
}}>上传</Button>
</div>
)
}
export default App;