index.vue 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <template>
  2. <el-dialog v-model="dialogVisible" title="批量导入" width="780px" append-to-body>
  3. <div class="describe-content">
  4. <div class="title">操作说明:</div>
  5. <div class="step-container">
  6. <el-steps direction="vertical">
  7. <el-step status="process" title="首先点击“模板下载,下载录入模板”" />
  8. <el-step status="process" :title="'在模板空白处中填写' + stepsText" />
  9. <el-step status="process" title="通过点击“浏览,选择导入文件,点击“导入”按钮,完成导入" />
  10. <el-step
  11. status="process"
  12. :title="'导入成功,对于系统中没有的' + stepsText + ',进行新增操作对于原本系统已存在的' + stepsText + ',进行信息合并操作。'"
  13. />
  14. </el-steps>
  15. </div>
  16. </div>
  17. <template #footer>
  18. <div class="dialog-footer">
  19. <el-upload
  20. ref="fileUploadRef"
  21. multiple
  22. :action="uploadFileUrl"
  23. :before-upload="handleBeforeUpload"
  24. :file-list="fileList"
  25. :limit="limit"
  26. :on-error="handleUploadError"
  27. :on-exceed="handleExceed"
  28. :on-success="handleUploadSuccess"
  29. :show-file-list="false"
  30. :headers="headers"
  31. :http-request="uploadFile"
  32. class="upload-file-uploader"
  33. >
  34. <el-button type="primary" :icon="Upload">导入</el-button>
  35. </el-upload>
  36. <el-button type="primary" :icon="Download" style="margin-left: 16px" @click="handleDownload">模板下载</el-button>
  37. </div>
  38. </template>
  39. </el-dialog>
  40. </template>
  41. <script lang="ts" setup name="DataImport">
  42. import { Upload, Download } from '@element-plus/icons-vue';
  43. import { download2, globalHeaders } from '@/utils/request';
  44. import { propTypes } from '@/utils/propTypes';
  45. import { v1 as uuidv1 } from 'uuid';
  46. import axios from 'axios';
  47. import { dataImport } from '@/api/PreventionResponsible';
  48. const props = defineProps({
  49. modelValue: Boolean,
  50. // 数量限制
  51. limit: propTypes.number.def(20),
  52. // 大小限制(MB)
  53. fileSize: propTypes.number.def(100),
  54. fileType: propTypes.array.def(['xls', 'xlsx']),
  55. stepsText: String,
  56. url: String,
  57. fileName: String
  58. });
  59. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  60. const emits = defineEmits(['update:modelValue']);
  61. const dialogVisible = computed({
  62. get() {
  63. return props.modelValue;
  64. },
  65. set(newValue) {
  66. emits('update:modelValue', newValue);
  67. }
  68. });
  69. const number = ref(0);
  70. const uploadList = ref<any[]>([]);
  71. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  72. const downLoadApi = import.meta.env.VITE_APP_BASE_DOWNLOAD_API;
  73. const uploadFileUrl = ref(baseUrl + '/resource/oss/upload'); // 上传文件服务器地址
  74. const headers = ref(globalHeaders());
  75. const fileList = ref<any[]>([]);
  76. const fileUploadRef = ref<ElUploadInstance>();
  77. // 隐藏清空数据
  78. watch(
  79. () => props.modelValue,
  80. async (val) => {
  81. if (!val) {
  82. fileList.value = [];
  83. }
  84. },
  85. { deep: true, immediate: true }
  86. );
  87. // 进入导入界面
  88. const handleImport = () => {
  89. };
  90. // 上传前校检格式和大小
  91. const handleBeforeUpload = (file: any) => {
  92. // 校检文件类型
  93. if (props.fileType.length) {
  94. const fileName = file.name.split('.');
  95. const fileExt = fileName[fileName.length - 1];
  96. const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
  97. if (!isTypeOk) {
  98. proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
  99. return false;
  100. }
  101. }
  102. // 校检文件大小
  103. if (props.fileSize) {
  104. const isLt = file.size / 1024 / 1024 < props.fileSize;
  105. if (!isLt) {
  106. proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
  107. return false;
  108. }
  109. }
  110. proxy?.$modal.loading('正在上传文件,请稍候...');
  111. number.value++;
  112. return true;
  113. };
  114. // 文件个数超出
  115. const handleExceed = () => {
  116. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  117. };
  118. // 上传失败
  119. const handleUploadError = () => {
  120. proxy?.$modal.msgError('上传文件失败');
  121. };
  122. const uploadFile = async ({ data, file }) => {
  123. // data是上传时附带的额外参数,file是文件
  124. let url = baseUrl + '/file/upload/uploadfile'; //上传文件接口
  125. try {
  126. // 如果文件大于等于5MB,分片上传
  127. data.file = file;
  128. const res = await uploadByPieces(url, data);
  129. // 分片上传后操作
  130. return res;
  131. } catch (e) {
  132. return e;
  133. }
  134. };
  135. //分片上传
  136. const uploadByPieces = async (url, { fileName, file }) => {
  137. // 上传过程中用到的变量
  138. const chunkSize = 5 * 1024 * 1024; // 5MB一片
  139. const chunkCount = Math.ceil(file.size / chunkSize); // 总片数
  140. // 获取当前chunk数据
  141. const identifier = uuidv1();
  142. const getChunkInfo = (file, index) => {
  143. let start = index * chunkSize;
  144. let end = Math.min(file.size, start + chunkSize);
  145. let chunknumber = file.slice(start, end);
  146. const fileName = file.name;
  147. return { chunknumber, fileName };
  148. };
  149. // 分片上传接口
  150. const uploadChunk = (data, params) => {
  151. return new Promise((resolve, reject) => {
  152. axios({
  153. url,
  154. method: 'post',
  155. data,
  156. params,
  157. headers: {
  158. 'Content-Type': 'multipart/form-data'
  159. }
  160. })
  161. .then((res) => {
  162. return resolve(res.data);
  163. })
  164. .catch((err) => {
  165. return reject(err);
  166. });
  167. });
  168. };
  169. // 针对单个文件进行chunk上传
  170. const readChunk = (index) => {
  171. const { chunknumber } = getChunkInfo(file, index);
  172. let fetchForm = new FormData();
  173. fetchForm.append('file', chunknumber);
  174. return uploadChunk(fetchForm, {
  175. chunknumber: index,
  176. identifier: identifier
  177. });
  178. };
  179. // 针对每个文件进行chunk处理
  180. const promiseList = [];
  181. try {
  182. for (let index = 0; index < chunkCount; ++index) {
  183. promiseList.push(readChunk(index));
  184. }
  185. await Promise.all(promiseList);
  186. // 文件分片上传完成后,调用合并接口
  187. const res = await mergeChunks(identifier, file.name);
  188. res.originalName = file.name;
  189. const res2 = await dataImport({
  190. filename: res.filename,
  191. file_name_desc: res.originalName,
  192. })
  193. return res;
  194. } catch (e) {
  195. return e;
  196. }
  197. };
  198. const mergeChunks = async (identifier: string, filename: string) => {
  199. try {
  200. const response = await axios.post(baseUrl + '/file/upload/mergefile', null, {
  201. params: {
  202. identifier: identifier,
  203. filename: filename,
  204. chunkstar: 0 // 假设所有分片的开始序号为0
  205. }
  206. });
  207. return response.data;
  208. } catch (error) {
  209. throw new Error('合并请求失败');
  210. }
  211. };
  212. // 上传成功回调
  213. const handleUploadSuccess = (res: any, file: UploadFile) => {
  214. if (res.code === 200) {
  215. uploadList.value.push({
  216. name: res.originalName,
  217. url: res.filename
  218. });
  219. uploadedSuccessfully();
  220. proxy.$modal.msgSuccess('导入成功');
  221. emits('update:modelValue', false);
  222. } else {
  223. number.value--;
  224. proxy?.$modal.closeLoading();
  225. proxy?.$modal.msgError(res.msg);
  226. fileUploadRef.value?.handleRemove(file);
  227. uploadedSuccessfully();
  228. proxy.$modal.msgError('导入失败');
  229. }
  230. };
  231. // 上传结束处理
  232. const uploadedSuccessfully = () => {
  233. if (number.value > 0 && uploadList.value.length === number.value) {
  234. fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  235. uploadList.value = [];
  236. number.value = 0;
  237. proxy?.$modal.closeLoading();
  238. }
  239. };
  240. // 下载模板
  241. const handleDownload = () => {
  242. if (!props.url) return false;
  243. download2(baseUrl + downLoadApi + props.url, props.fileName);
  244. };
  245. </script>
  246. <style lang="scss" scoped>
  247. .title {
  248. font-size: 18px;
  249. line-height: 36px;
  250. margin-bottom: 10px;
  251. color: rgba(0, 0, 0, 0.85);
  252. }
  253. .step-container {
  254. width: 700px;
  255. height: 180px;
  256. :deep(.el-step) {
  257. .el-step__icon.is-text {
  258. border-color: #a8abb2;
  259. color: rgba(0, 0, 0, 0.85);
  260. }
  261. .el-step__title.is-process {
  262. font-size: 16px;
  263. color: rgba(0, 0, 0, 0.85);
  264. font-weight: normal;
  265. }
  266. }
  267. }
  268. .upload-file-list .el-upload-list__item {
  269. line-height: 22px;
  270. margin-bottom: 10px;
  271. position: relative;
  272. padding: 3px 5px;
  273. }
  274. .upload-file-list .ele-upload-list__item-content {
  275. display: flex;
  276. align-items: center;
  277. color: inherit;
  278. }
  279. .ele-upload-list__item-content-action .el-link {
  280. margin-right: 10px;
  281. }
  282. </style>