通過覆蓋默認(rèn)的上傳行為,可以自定義自己的上傳實(shí)現(xiàn)
自定義的上傳步驟
- 調(diào)用預(yù)上傳接口拿到上傳地址與對(duì)象存儲(chǔ)id
- 使用put方法上傳文件并帶上存儲(chǔ)id
// 定義變量與方法, 方便描述
const PRE_UPLOAD_URL // 預(yù)上傳地址
const UPLOAD_URL // 上傳地址
const objectID // 對(duì)象存儲(chǔ)id
const parseSearchString // 格式化url參數(shù)為對(duì)象的方法
const toSearchString // 格式化對(duì)象為url參數(shù)的方法
const getUrlByObjectID // 通過對(duì)象存儲(chǔ)id拿url的方法
const uuid // 生成唯一id的方法
const Uploader = ({ onChange, value, children, ...props }) => {
// 初始化初始值
useEffect(() => {
if (!value) return;
const fileList = value.map((fileInfo) => {
const { name, objectID, } = fileInfo
const uid = uuid()
return {
status: "done", // 初始值文件的狀態(tài)
url: getUrlByObjectID(fileInfo.objectID), // 獲取顯示圖片的url
uid, // 內(nèi)部唯一id
name, // 文件名稱
objectID
}
});
// 更新
onChange && onChange(fileList);
}, []);
return (
<Upload
action={(file) => {
return new Promise((c, e) => {
// 請(qǐng)求預(yù)上傳地址,拿到上傳地址與id
axios.get(PRE_UPLOAD_URL).then(
(res) => {
const data = res.data;
const { UPLOAD_URL, objectID } = data;
const [base, queryStr] = UPLOAD_URL.split("?");
const query = {
objectID, // 把id通過query的方式傳遞
...parseSearchString(queryStr),
};
c(`${base}${toSearchString(query)}`);
},
() => {
e("上傳失敗");
},
);
});
}}
customRequest={(e) => {
const [url, queryStr] = e.action.split("?");
const query = parseSearchString(queryStr);
// 取出對(duì)象存儲(chǔ)id
const { objectID = "", ...other } = query;
const file = e.file;
const name = file.name; // 文件名字
組裝上傳地址
const action = `${url}${toSearchString(other)}`;
axios
.put(action, file, {
// 顯示進(jìn)度
onUploadProgress: (ev) => {
const percent = ((ev.loaded / ev.total) * 100) | 0;
e.onProgress(
{
percent,
},
file,
);
},
})
.then(
() => {
const url = getUrlByObjectID(objectID)
// 上傳成功
e.onSuccess(
{
objectID,
name,
url,
},
file,
);
},
(res) => {
e.onError(res);
},
);
}}
onChange={({ event, fileList }) => {
if (event && event.percent === 100) {
// 這里100%后不能正常拿到上傳的對(duì)象 需要延遲處理
setTimeout(() => {
// 上面onSuccess傳遞的參數(shù)會(huì)被包裹在response中
let value = fileList.map(({ response, uid }) => ({ ...response, uid }));
onChange && onChange(value);
}, 1000);
}
}}
method="put"
{...props}
/>
);
};
在form中使用
<Form.Item name="upload" label="上傳圖片">
<Uploader listType="picture">
<Button>
<UploadOutlined /> 上傳圖標(biāo)
</Button>
</Uploader>
</Form.Item>