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

100 lines
2.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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";
/**
* 上传文件
*/
function useUploadFile(returnType = "object") {
// loading状态
const [loading, setLoading] = useState(false);
// 上传文件
const uploadFile = (options) => {
if (!options)
throw new Error("请传入 options");
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");
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);
// 获取待上传的文件
const filesLength = formData.getAll("files").length;
// 如果没有文件则返回老文件
if (filesLength === 0) {
setLoading(false);
resolve(
single
? { filePath: files[0].filePath }
: { id: params.foreignKey },
);
return;
}
// 发送请求
request(
single ? "/basic-info/imgFiles/save" : "/basic-info/imgFiles/batchSave",
"post",
formData,
{ "Content-Type": "multipart/form-data" },
)
.then((res) => {
resolve(
single
? { filePath: res.data.filePath }
: { id: res.data.foreignKey },
);
})
.catch((err) => {
reject(err);
})
.finally(() => {
setLoading(false);
});
});
};
if (returnType === "array")
return [loading, uploadFile];
return { loading, uploadFile };
}
export default useUploadFile;