zy-react-library/hooks/useUploadFile/index.js

100 lines
2.7 KiB
JavaScript
Raw Normal View History

2025-10-28 11:28:18 +08:00
import { request } from "@cqsjjb/jjb-common-lib/http";
import { useState } from "react";
import { UPLOAD_FILE_PATH_ENUM, UPLOAD_FILE_TYPE_ENUM } from "../../enum/uploadFile/gwj";
2025-10-28 11:28:18 +08:00
/**
* 上传文件
2025-10-28 11:28:18 +08:00
*/
function useUploadFile(returnType = "object") {
2025-10-28 11:28:18 +08:00
// loading状态
const [loading, setLoading] = useState(false);
// 上传文件
const uploadFile = (options) => {
if (!options)
throw new Error("请传入 options");
2025-10-28 11:28:18 +08:00
setLoading(true);
return new Promise((resolve, reject) => {
const { files, single = true, params } = options;
if (!files)
throw new Error("请传入 files");
if (!params)
throw new Error("请传入 options.params");
if (!params.type)
throw new Error("请传入 options.params.type");
// 检查type是否在UPLOAD_FILE_TYPE_ENUM中
if (!Object.values(UPLOAD_FILE_TYPE_ENUM).includes(params.type))
throw new Error("传入的 type 不在 UPLOAD_FILE_TYPE_ENUM 中");
// 根据type获取对应的path
const path = UPLOAD_FILE_PATH_ENUM[params.type];
if (!path)
throw new Error(`未找到 type ${params.type} 对应的 path `);
// 当single为false时foreignKey是必需的
if (!single && (params.foreignKey === undefined || params.foreignKey === null))
throw new Error("请传入 options.params.foreignKey");
2025-10-28 11:28:18 +08:00
const formData = new FormData();
// 将文件添加到formData中
files.forEach((f) => {
f.originFileObj && formData.append("files", f.originFileObj);
});
// 将额外携带的参数添加到formData中
Object.keys(params).forEach((key) => {
formData.append(key, params[key]);
});
// 添加path参数
formData.append("path", path);
2025-10-28 11:28:18 +08:00
// 获取待上传的文件
const filesLength = formData.getAll("files").length;
// 如果没有文件则返回老文件
if (filesLength === 0) {
setLoading(false);
resolve(
single
? { filePath: files[0].filePath }
: { id: params.foreignKey },
2025-10-28 11:28:18 +08:00
);
return;
}
// 发送请求
request(
single ? "/basic-info/imgFiles/save" : "/basic-info/imgFiles/batchSave",
"post",
formData,
{ "Content-Type": "multipart/form-data" },
)
2025-10-28 11:28:18 +08:00
.then((res) => {
resolve(
single
? { filePath: res.data.filePath }
: { id: res.data.foreignKey },
2025-10-28 11:28:18 +08:00
);
})
.catch((err) => {
reject(err);
})
.finally(() => {
setLoading(false);
});
});
};
if (returnType === "array")
return [loading, uploadFile];
return { loading, uploadFile };
2025-10-28 11:28:18 +08:00
}
export default useUploadFile;