safety-eval-service-frontend/src/components/AttachmentUpload/index.js

86 lines
2.5 KiB
JavaScript

import { Form, Image, Upload } from "antd";
import { useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
const isImage = (url) =>
/\.(png|jpe?g|gif|bmp|webp|svg)(\?.*)?$/i.test(url || "");
export default function AttachmentUpload({ name, label, disabled = false, maxCount, accept }) {
const [previewImage, setPreviewImage] = useState("");
return (
<>
<Form.Item
name={name}
label={label}
valuePropName="fileList"
getValueProps={(value) => {
if (Array.isArray(value)) {
return { fileList: value };
}
if (typeof value === "string" && value) {
try {
const parsed = JSON.parse(value);
if (Array.isArray(parsed)) {
return { fileList: parsed };
}
} catch {}
return {
fileList: value.split(",").map((item) => ({
url: item,
uid: item,
status: "done",
name: "附件",
})),
};
}
return { fileList: [] };
}}
getValueFromEvent={({ fileList }) => {
return (
fileList?.map((file) => ({
url: file.response?.data?.url || file.url,
uid: file.uid,
status: file.status,
name: file.name,
percent: file.percent,
})) || []
);
}}
>
<Upload
//disabled={disabled}
listType="picture-card"
headers={{
token: sessionStorage.getItem('token')
}}
maxCount={maxCount}
accept={accept}
action={`${window.process.env.app.API_HOST}/safetyEval/file/upload`}
onPreview={(file) => {
if (isImage(file.url || file.thumbUrl)) {
setPreviewImage(file.url || file.thumbUrl);
} else {
window.open(file.url || file.thumbUrl);
}
}}
>
<button style={{ border: 0, background: "none" }} type="button">
<PlusOutlined />
<div style={{ marginTop: 8 }}>上传附件</div>
</button>
</Upload>
</Form.Item>
<Image
style={{ display: "none" }}
preview={{
visible: !!previewImage,
src: previewImage,
onVisibleChange: (visible) => {
if (!visible) setPreviewImage("");
},
}}
/>
</>
);
}