UploadTexture.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //上传封面组件
  2. import _React, { useState } from "react";
  3. import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
  4. import { message, Upload } from "antd";
  5. import type { UploadChangeParam } from "antd/es/upload";
  6. import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
  7. const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  8. const reader = new FileReader();
  9. reader.addEventListener("load", () => callback(reader.result as string));
  10. reader.readAsDataURL(img);
  11. };
  12. const beforeUpload = (file: RcFile) => {
  13. const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  14. if (!isJpgOrPng) {
  15. message.error("You can only upload JPG/PNG file!");
  16. }
  17. const isLt2M = file.size / 1024 / 1024 < 2;
  18. if (!isLt2M) {
  19. message.error("Image must smaller than 2MB!");
  20. }
  21. return isJpgOrPng && isLt2M;
  22. };
  23. const UploadTextureWidget = () => {
  24. const [loading, setLoading] = useState(false);
  25. const [imageUrl, setImageUrl] = useState<string>();
  26. const handleChange: UploadProps["onChange"] = (
  27. info: UploadChangeParam<UploadFile>
  28. ) => {
  29. if (info.file.status === "uploading") {
  30. setLoading(true);
  31. return;
  32. }
  33. if (info.file.status === "done") {
  34. // Get this url from response in real world.
  35. getBase64(info.file.originFileObj as RcFile, (url) => {
  36. setLoading(false);
  37. setImageUrl(url);
  38. });
  39. }
  40. };
  41. const uploadButton = (
  42. <div>
  43. {loading ? <LoadingOutlined /> : <PlusOutlined />}
  44. <div style={{ marginTop: 8 }}>Upload</div>
  45. </div>
  46. );
  47. return (
  48. <Upload
  49. name="avatar"
  50. listType="picture-card"
  51. className="avatar-uploader"
  52. showUploadList={false}
  53. beforeUpload={beforeUpload}
  54. onChange={handleChange}
  55. >
  56. {imageUrl ? (
  57. <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
  58. ) : (
  59. uploadButton
  60. )}
  61. </Upload>
  62. );
  63. };
  64. export default UploadTextureWidget;