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、安装中间件
2、Upload服务端代码
前端发起请求后即可得到返回的图片名称,然后自行拼接图片地址(由baseUrl与返回的地址组成)即可。
3、Upload前端开发
主要使用antd的Upload组件(省略部分代码):
最后更新于
这有帮助吗?