前端代码
//引入antd组件import { Upload, message } from 'antd';import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';class Avatar extends React.Component { state = { loading: false, }; //判断要上传的图片格式和大小,返回true继续上传,返回false终止上传 beforeUpload(file) { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJpgOrPng) { message.error('You can only upload JPG/PNG file!'); } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { message.error('Image must smaller than 2MB!'); } return isJpgOrPng && isLt2M; } customRequest() { } render() { const { loading, imageUrl } = this.state; // loading,图片上传过程中显示的loading const uploadButton = ( <div> {loading ? <LoadingOutlined /> : <PlusOutlined />} <div style={{ marginTop: 8 }}>Upload</div> </div> ); return ( //重要代码,调用antd的上传组件 <Upload name="avatar" listType="picture-card" className="avatar-uploader" showUploadList={false} action="请求路径" beforeUpload={(file)=>{this.beforeUpload(file)}} //在上传之前做一些判断 customRequest={()=>{this.customRequest()}} //自定义上传事件处理函数 > {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton} </Upload> ); }}
后端代码
//使用nodejs加egg// router.js router.post('/user/upload', controller.user.upload);// controller async upload() { const { ctx } = this; const file = ctx.request.files[0]; //获取前端传入的文件信息 const uploadError = await ctx.service.user.upload(file) if (uploadError) { ctx.status = 403; ctx.body = { code: 0, msg: '上传失败!', result: uploadError, }; } else { ctx.status = 200; ctx.body = { code: 0, msg: '上传成功!', imgUrl: `http://localhost:70001/images/upload/${file.name}`, //返回图片路径 } } }// service async upload(file) { //使用fs模块进行读文件和写文件, const uploadData = fs.readFileSync(file.path); // 把上传的图片放在egg的public静态资源目录下。 const uploadDir = path.join(process.cwd(), '/app/public/upload', file.name); const uploadError = fs.writeFileSync(uploadDir, uploadData); return uploadError; }