Skip to content

Commit

Permalink
fix:修复上传文件逻辑处理
Browse files Browse the repository at this point in the history
  • Loading branch information
YWzzy committed Jul 26, 2024
1 parent 36197f9 commit 0bf5f97
Show file tree
Hide file tree
Showing 8 changed files with 242 additions and 101 deletions.
3 changes: 2 additions & 1 deletion monitor_admin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"inquirer": "^10.1.2",
"js-base64": "^3.7.3",
"lodash": "^4.17.21",
"p-limit": "^6.1.0",
"pako": "^2.1.0",
"prismjs": "^1.29.0",
"react": "^18.3.1",
Expand Down Expand Up @@ -66,4 +67,4 @@
"typescript": "^5.2.2",
"vite": "^5.3.1"
}
}
}
6 changes: 5 additions & 1 deletion monitor_admin/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,8 @@ export const uploadDistFiles = async (data: FormData): CustomResponse<any> =>

// 查询项目包文件
export const findDistPackages = async (params: any): CustomResponse<any> =>
await http.get('/dist-upload/findDistPackages', { params });
await http.get('/dist-upload/findDistPackages', { params });

// 上传包之前 - 获取上传批次信息
export const getUploadBatch = async (params: any): CustomResponse<any> =>
await http.get('/dist-upload/getUploadBatch', { params });
92 changes: 67 additions & 25 deletions monitor_admin/src/components/configApplication/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Switch, message, Spin, Button, Upload, UploadFile, Row, Col, Card, Radio } from 'antd';
import { updateAppConfig, uploadDistFiles } from '@/src/api';
import { getUploadBatch, updateAppConfig, uploadDistFiles } from '@/src/api';
import { useAppStore, useUserStore } from '@/src/hooks';
import { UploadOutlined, CloseOutlined } from '@ant-design/icons';
import { ProjectEnvType, ProjectEnvTypes } from '@/src/constants';
import pLimit from 'p-limit';

interface ConfigApplicationIn {
open: boolean;
Expand Down Expand Up @@ -65,39 +66,80 @@ export const ConfigApplication: React.FC<ConfigApplicationIn> = ({ open, onClose
// 清除dist文件
const clearDistFiles = () => {
setFileList([]);
}
};

// 上传单个文件
const uploadSingleFile: any = async (file: UploadOriginFile, formData: FormData) => {
formData.set(`webkitRelativePath`, file['webkitRelativePath']);
formData.set('fileName', file.name);
formData.set('fileSize', String(file.size));
formData.set('file', file.originFileObj as Blob);
try {
const response = await uploadDistFiles(formData);
return { status: 'fulfilled', data: response };
} catch (error) {
throw new Error(`文件 ${file.name} 上传失败`);
}
};

// 上传dist文件
const handleUpload = async () => {
message.open({
content: '文件上传中...',
key: 'uploading',
});
const formData = new FormData();
const formLocalData = form.getFieldsValue();
const webkitRelativePathMap = new Map();
const isSourceMap = formLocalData['isSourceMap'];
fileList.forEach((file) => {
formData.append('files', file.originFileObj as Blob);
webkitRelativePathMap.set(file.originFileObj.name + file.originFileObj.size, file.webkitRelativePath);
});
formData.append(`webkitRelativePathMap`, JSON.stringify(Object.fromEntries(webkitRelativePathMap)));
formData.append('appId', appConfig['appId']);
formData.append('projectEnv', formLocalData['projectEnv']);
formData.append('projectVersion', formLocalData['projectVersion']);
formData.append('isSourceMap', isSourceMap);
formData.append('userId', import.meta.env.VITE_USERID);

setUploading(true);
try {
await uploadDistFiles(formData);
message.success('文件上传成功!');
setFileList([]); // 清空文件列表
} catch (error) {
message.error('文件上传失败!');
} finally {
setUploading(false);
const params = {
appId: appConfig['appId'],
projectEnv: form.getFieldValue('projectEnv'),
projectVersion: form.getFieldValue('projectVersion'),
isSourceMap: form.getFieldValue('isSourceMap'),
userId: import.meta.env.VITE_USERID,
filesNumber: fileList.length,
filesSize: fileList.reduce((acc, file) => acc + file.size, 0),
}
// 获取上传批次,成功后上传文件
await getUploadBatch(params).then(async (res) => {
if (res.code === 200) {
const formData = new FormData();
const { appId, isSourceMap, projectEnv, projectVersion, rootPath, userId, logId } = res.data;
formData.append('appId', appId);
formData.append('projectEnv', projectEnv);
formData.append('projectVersion', projectVersion);
formData.append('isSourceMap', isSourceMap);
formData.append('userId', userId);
formData.append('logId', logId);
formData.append('rootPath', rootPath);

const limit = pLimit(8);
const uploadPromises = fileList.map(file => limit(() => uploadSingleFile(file, formData)));
try {
const uploadRes = await Promise.all(uploadPromises);
const fulfilledUploads = uploadRes.filter(result => result.status === 'fulfilled');
const rejectedUploads = uploadRes.filter(result => result.status === 'rejected');

if (rejectedUploads.length > 0) {
const errors = rejectedUploads.map(result => result.reason.message).join(', ');
message.error(`部分文件上传失败: ${errors}`);
}

if (fulfilledUploads.length > 0) {
message.success('文件上传成功!');
}
setFileList([]); // 清空文件列表
} catch (error) {
message.error(`文件上传失败:${error.message}`);
} finally {
setUploading(false);
}
}
}).catch((error) => {
message.error(`获取上传批次失败:${error.message}`);
}).finally(() => {
message.destroy('uploading');
setUploading(false);
});
};

const uploadProps = {
Expand All @@ -110,7 +152,6 @@ export const ConfigApplication: React.FC<ConfigApplicationIn> = ({ open, onClose
beforeUpload: (file: UploadOriginFile) => {
const formLocalData = form.getFieldsValue();
const isSourceMap = formLocalData['isSourceMap'];
// const isSourceMap = appConfig['isSourceMap'];
const allowedNonSourceMapExtensions = ['.js', '.jsx', '.tsx', '.ts', '.cjs', '.scss', '.less', '.css', '.html', '.htm'];

const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
Expand All @@ -125,6 +166,7 @@ export const ConfigApplication: React.FC<ConfigApplicationIn> = ({ open, onClose
const uploadFile: any = {
uid: file.uid,
name: file.name,
size: file.size,
status: 'done',
originFileObj: file,
webkitRelativePath: file.webkitRelativePath,
Expand Down
12 changes: 12 additions & 0 deletions monitor_admin/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3381,6 +3381,13 @@ p-limit@^3.0.2:
dependencies:
yocto-queue "^0.1.0"

p-limit@^6.1.0:
version "6.1.0"
resolved "https://registry.npmjs.org/p-limit/-/p-limit-6.1.0.tgz#d91f9364d3fdff89b0a45c70d04ad4e0df30a0e8"
integrity sha512-H0jc0q1vOzlEk0TqAKXKZxdl7kX3OFUzCnNVUnq5Pc3DGo0kpeaMuPqxQn235HibwBEb0/pm9dgKTjXy66fBkg==
dependencies:
yocto-queue "^1.1.1"

p-locate@^5.0.0:
version "5.0.0"
resolved "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz"
Expand Down Expand Up @@ -4412,6 +4419,11 @@ yocto-queue@^0.1.0:
resolved "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz"
integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==

yocto-queue@^1.1.1:
version "1.1.1"
resolved "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.1.1.tgz#fef65ce3ac9f8a32ceac5a634f74e17e5b232110"
integrity sha512-b4JR1PFR10y1mKjhHY9LaGo6tmrgjit7hxVIeAmyMw3jegXR4dhYqLaQF5zMXZxY7tLpMyJeLjr1C4rLmkVe8g==

yoctocolors-cjs@^2.1.2:
version "2.1.2"
resolved "https://registry.npmjs.org/yoctocolors-cjs/-/yoctocolors-cjs-2.1.2.tgz#f4b905a840a37506813a7acaa28febe97767a242"
Expand Down
49 changes: 40 additions & 9 deletions server/src/dist-upload/dist-upload.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,47 +30,78 @@ import { Auth } from "src/decorator/Auth";
@ApiTags("DistUpload")
@Controller("dist-upload")
export class DistUploadController {
constructor(private readonly distUploadService: DistUploadService) {}
constructor(private readonly distUploadService: DistUploadService) { }


@Get('getUploadBatch')
@ApiOperation({ summary: "获取上传批次信息" })
@Auth()
async getUploadBatch(
@Query('appId') appId: string,
@Query('projectEnv') projectEnv: string,
@Query('projectVersion') projectVersion: string,
@Query('isSourceMap') isSourceMap: boolean,
@Query('userId') userId: string,
@Query('filesNumber') filesNumber: string,
@Query('filesSize') filesSize: string
): Promise<{ logId: string }> {
try {
return await this.distUploadService.getUploadBatch(appId, projectEnv, projectVersion, isSourceMap, userId, filesNumber, filesSize);
} catch (error) {
throw new CustomHttpException(error.status, error.message);
}
}

@Post("upload")
@ApiOperation({ summary: "上传dist包" })
@ApiConsumes("multipart/form-data")
@UseInterceptors(FilesInterceptor("files"))
@UseInterceptors(FilesInterceptor("file"))
@ApiBody({
schema: {
type: "object",
properties: {
appId: { type: "string" },
projectEnv: { type: "string" },
logId: { type: "string" },
rootPath: { type: "string" },
projectVersion: { type: "string" },
isSourceMap: { type: "boolean" },
userId: { type: "string" },
files: { type: "array", items: { type: "string", format: "binary" } },
fileName: { type: "string" },
file: { type: "string", format: "binary" },
},
},
})
@Auth()
async uploadDistPackage(
@Body() body: any,
@UploadedFiles() files: Express.Multer.File[]
): Promise<DistUploadLog> {
@UploadedFiles() file: Express.Multer.File
): Promise<DistUpload> {
try {
const {
appId,
projectEnv,
projectVersion,
webkitRelativePathMap,
webkitRelativePath,
isSourceMap,
userId,
rootPath,
logId,
fileName,
fileSize,
} = body;
return await this.distUploadService.uploadDistPackage(
appId,
files,
webkitRelativePathMap,
file,
webkitRelativePath,
projectEnv,
projectVersion,
isSourceMap,
userId
userId,
rootPath,
logId,
fileName,
fileSize
);
} catch (error) {
throw new CustomHttpException(
Expand Down
Loading

0 comments on commit 0bf5f97

Please sign in to comment.