Part6-前后端图片上传
前端使用React+Antd+TS,后端使用Koa2.
一、Upload组件
Ant Design中使用 Upload 组件进行上传。但Ant Design中使用的是Class Component,这里对其进行改造为Function Component:
import React, { useState } from 'react'
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
// 上传前校验
function beforeUpload(file: { type: string; size: number; }) {
// 图片后缀名判断
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/gif';
if (!isJpgOrPng) {
message.error('只能上传jpg/png/jpeg/gif类型的图片');
}
const isLt2M = file.size / 1024 < 200;
if (!isLt2M) {
message.error('图片大小必须小于200K');
}
return isJpgOrPng && isLt2M;
}
const Home = () => {
const [loading, setLoading] = useState(false);
const [imageUrl, setImageUrl] = useState("");
const handleChange = (info: any) => {
if (info.file.status === 'uploading') {
setLoading(true);
return;
}
if (info.file.status === 'done') {
// 上传成功
setImageUrl(imageUrl);
setLoading(false);
}
};
const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}>Upload</div>
</div>
);
return (
<Upload
name= "avatar"
listType= "picture-card"
className= "avatar-uploader"
showUploadList= {false}
action= "后端地址"
headers={
{"token": localStorage.getItem("token") as string}
}
beforeUpload= {beforeUpload}
onChange= {handleChange}
>
{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
</Upload>
)
}
export default Home;
二、服务端图片上传
服务端处理图片/文件上传,主要使用koa的中间件:@koa/multer,具体的配置需要看 multer中间件的文档。
1、安装中间件
$ npm i @koa/multer multer
# 或者
$ yarn add @koa/multer multer
2、Upload服务端代码
const Router = require("koa-router")
const router = new Router();
const { query, msgFormat } = require("../../utils")
const fs = require("fs");
const multer = require('koa-multer');//加载koa-multer模块
const path = require("path")
const jwt = require('jsonwebtoken');
let myfilename = ""; // 返回给前端的文件名
// 创建存放头像图片的目录(当头像目录不存在时)
fs.readdir(__dirname + "/images/", function (err, files) {
if (err) {
fs.mkdir(__dirname + "/images/", function (err) {
if (err) {
console.log(err)
}
console.log("目录创建成功。");
})
}
})
var storage = multer.diskStorage({
//文件保存路径
destination: function (req, file, cb) {
cb(null, path.join(__dirname ,'/images/'))
},
//修改文件名称
filename: function (req, file, cb) {
let type = file.originalname.split('.')[1]
// logo.png -> logo.xxx.png
myfilename = `${file.fieldname}-${Date.now().toString(16)}.${type}`
cb(null, myfilename)
}
})
//文件上传限制
const limits = {
fields: 10,//非文件字段的数量
fileSize: 200 * 1024,//文件大小 单位 b
files: 1//文件数量
}
const upload = multer({storage,limits})
router.post('/', upload.single('avatar'), async ctx => {
// 当前接口允许跨域
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
// 获取文件
// console.log(ctx.req.file);
// 验证token
let token = ctx.request.headers["cms-token"];
...
// 查询token对应的用户
...
// 数组长度为0,代表这个token查询不到任何用户
...
let result = await new Promise((resolve, reject) => {
// 获取token对应的用户
const sql = `UPDATE user SET avatar='${myfilename}' WHERE token='${token}'`;
query(sql, (err, data) => {
if (err) reject(err);
resolve(true);
})
})
if(result){
ctx.body = msgFormat(0, '图片上传成功', {
// 要求前端自行补全域名
filePath: `${myfilename}`
})
}else{
ctx.body = msgFormat(1, '操作失败请重试');
}
})
module.exports = router
前端发起请求后即可得到返回的图片名称,然后自行拼接图片地址(由baseUrl与返回的地址组成)即可。
3、Upload前端开发
主要使用antd的Upload组件(省略部分代码):
import React, { useState, useEffect } from "react";
import { Upload, message, Form, Input, Button } from "antd";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
// 上传之前校验图片后缀与大小
function beforeUpload(file: { type: string; size: number }) {
const isJpgOrPng =
file.type === "image/jpeg" || file.type === "image/png" || file.type === "image/jpg" || file.type === "image/gif";
if (!isJpgOrPng) {
message.error("上传图片的后缀必须是:jpeg/png/jpg/gif");
}
// const isLt2M = file.size / 1024 / 1024 < 2;
const isLt2K = file.size / 1024 / 1024 / 1024 < 200;
if (!isLt2K) {
message.error("图片大小不得超过200KB");
}
return !isJpgOrPng && !isLt2K;
}
const Means = () => {
const [loading, setLoading] = useState(false);
const [imageUrl, setImageUrl] = useState(localStorage.getItem("avatar") || "default_avatar.png");
// 上传文件改变时的状态
const handleChange = (info: any) => {
if (info.file.status === "uploading") {
setLoading(true);
}
if (info.file.status === "done") {
setLoading(false);
setImageUrl(info.file.response.data.filePath);
localStorage.setItem("avatar", `${info.file.response.data.filePath}`)
}
};
const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}>上传头像</div>
</div>
);
interface IUploadProps {
name: string;
showUploadList: boolean;
maxCount: number;
headers: { "cms-token": string };
action: string;
enctype: string;
beforeUpload: any;
onChange: any;
listType: any;
}
// upload组件的属性
const uploadProps: IUploadProps = {
name: "avatar",
showUploadList: false,
listType: "picture-card",
maxCount: 1,
headers: {
"cms-token": localStorage.getItem("cms-token") || "",
},
enctype: "multipart/form-data",
action: "http://localhost:9000/manage/upload",
beforeUpload: () => beforeUpload,
onChange: (info: any) => handleChange(info)
};
return (
<>
...
<Upload {...uploadProps}>
{imageUrl ? (
<img src={"http://localhost:9000/" + imageUrl} alt="用户头像" style={{ width: "100%" }} />
) : (
uploadButton
)}
</Upload>
</>
);
};
export default Means;
最后更新于
这有帮助吗?