antd 里面的Upload图片上传

àì夳堔傛蜴生んèń 2023-07-05 13:12 183阅读 0赞

Antd 里面的Upload

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L01pc3NfbGlhbmdybQ_size_16_color_FFFFFF_t_70

  1. import React,{useState} from 'react';
  2. import { Upload, Icon, message,Spin } from 'antd';
  3. import serviceApi from '@/utils/api';
  4. import {MessageTip} from '@/utils/tools.js'
  5. import './upload.css'
  6. // 上传单张图片
  7. function getBase64(img, callback) {
  8. const reader = new FileReader();
  9. reader.addEventListener('load', () => callback(reader.result));
  10. reader.readAsDataURL(img);
  11. }
  12. function beforeUpload(file) {
  13. const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  14. if (!isJpgOrPng) {
  15. message.error('仅支持JPG/PNG格式的图片');
  16. }
  17. const isLt2M = file.size / 1024 / 1024 < 2;
  18. if (!isLt2M) {
  19. message.error('图片大小不能超过 2MB!');
  20. }
  21. return isJpgOrPng && isLt2M;
  22. }
  23. const UploadAvatar = (props) =>{
  24. const [loading,setLoading] = useState(false)
  25. const [imageUrl,setImageUrl] = useState('')
  26. const handleChange = info => {
  27. if (info.file.status === 'uploading') {
  28. setLoading(true)
  29. return;
  30. }
  31. if (info.file.status === 'done') {
  32. getBase64(info.file.originFileObj, imageUrl =>{
  33. setLoading(false)
  34. if(info.file.response.success){
  35. const {module} = info.file.response // 返回的图片地址
  36. props.childImg(module) // 传给父级的
  37. setImageUrl(imageUrl)
  38. MessageTip('success','文件上传成功')
  39. }
  40. });
  41. }
  42. };
  43. const uploadButton = (
  44. <div>
  45. {
  46. loading?<Spin />:''
  47. }
  48. <div className="ant-upload-text">Upload</div>
  49. </div>
  50. );
  51. return (
  52. <Upload
  53. name="file"
  54. listType="picture-card"
  55. className="avatar-uploader"
  56. showUploadList={false}
  57. action={serviceApi.uploadFile}
  58. data={
  59. {type:1}} // type 1图片 2试卷
  60. beforeUpload={beforeUpload}
  61. onChange={handleChange}
  62. >
  63. {imageUrl ? <img src={imageUrl} alt="avatar" style={
  64. { width: '100%' }} /> : uploadButton}
  65. </Upload>
  66. );
  67. }
  68. export default UploadAvatar;

发表评论

表情:
评论列表 (有 0 条评论,183人围观)

还没有评论,来说两句吧...

相关阅读