前端代码

  1. //引入antd组件
  2. import { Upload, message } from 'antd';
  3. import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
  4. class Avatar extends React.Component {
  5. state = {
  6. loading: false,
  7. };
  8. //判断要上传的图片格式和大小,返回true继续上传,返回false终止上传
  9. beforeUpload(file) {
  10. const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  11. if (!isJpgOrPng) {
  12. message.error('You can only upload JPG/PNG file!');
  13. }
  14. const isLt2M = file.size / 1024 / 1024 < 2;
  15. if (!isLt2M) {
  16. message.error('Image must smaller than 2MB!');
  17. }
  18. return isJpgOrPng && isLt2M;
  19. }
  20. customRequest() {
  21. }
  22. render() {
  23. const { loading, imageUrl } = this.state;
  24. // loading,图片上传过程中显示的loading
  25. const uploadButton = (
  26. <div>
  27. {loading ? <LoadingOutlined /> : <PlusOutlined />}
  28. <div style={{ marginTop: 8 }}>Upload</div>
  29. </div>
  30. );
  31. return (
  32. //重要代码,调用antd的上传组件
  33. <Upload
  34. name="avatar"
  35. listType="picture-card"
  36. className="avatar-uploader"
  37. showUploadList={false}
  38. action="请求路径"
  39. beforeUpload={(file)=>{this.beforeUpload(file)}} //在上传之前做一些判断
  40. customRequest={()=>{this.customRequest()}} //自定义上传事件处理函数
  41. >
  42. {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
  43. </Upload>
  44. );
  45. }
  46. }

后端代码

  1. //使用nodejs加egg
  2. // router.js
  3. router.post('/user/upload', controller.user.upload);
  4. // controller
  5. async upload() {
  6. const { ctx } = this;
  7. const file = ctx.request.files[0]; //获取前端传入的文件信息
  8. const uploadError = await ctx.service.user.upload(file)
  9. if (uploadError) {
  10. ctx.status = 403;
  11. ctx.body = {
  12. code: 0,
  13. msg: '上传失败!',
  14. result: uploadError,
  15. };
  16. } else {
  17. ctx.status = 200;
  18. ctx.body = {
  19. code: 0,
  20. msg: '上传成功!',
  21. imgUrl: `http://localhost:70001/images/upload/${file.name}`, //返回图片路径
  22. }
  23. }
  24. }
  25. // service
  26. async upload(file) {
  27. //使用fs模块进行读文件和写文件,
  28. const uploadData = fs.readFileSync(file.path);
  29. // 把上传的图片放在egg的public静态资源目录下。
  30. const uploadDir = path.join(process.cwd(), '/app/public/upload', file.name);
  31. const uploadError = fs.writeFileSync(uploadDir, uploadData);
  32. return uploadError;
  33. }