Commit 32fdb369 by chenjinjing

no message

parent 23bd4697
......@@ -7,6 +7,7 @@
"@alicloud/sms-sdk": "^1.1.6",
"@types/express": "^5.0.0",
"@types/node": "^10.12.18",
"archiver": "^7.0.1",
"compression": "^1.7.4",
"express": "^4.21.2",
"express-async-handler": "^1.1.4",
......@@ -18,7 +19,7 @@
"lru-cache": "^4.1.5",
"md5": "^2.2.1",
"moment": "^2.24.0",
"node-xlsx": "^0.16.1",
"node-xlsx": "^0.16.2",
"nodemailer": "^6.1.1",
"qs": "^6.11.0",
"request": "^2.88.0",
......@@ -27,7 +28,6 @@
"ws": "^5.2.2",
"xml2js": "^0.4.23"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
......
<config>
<port>13281</port>
<port>9097</port>
<sign>xxx90909082fsdahfjosadjfpoiwausjorip2hjklrhn1ioud0u124rx0qwejfokasjfolksaujfoas</sign>
<dbServer>http://192.168.0.71:40012</dbServer>
<fileIP>http://192.168.0.71:40004</fileIP>
......
......@@ -58,6 +58,13 @@ export async function authentication(req, res, next) {
if (!userInfo.token || userInfo.token != token) return next(new BizError(ERRORENUM.身份验证过期));
return next();
} else if (req.originalUrl == "/file/admin/zipdownload/consolidated") {
const Sign = req.headers.sign;
let sysSign = 'isdfalfdjasoiufoisjdlnad29230428029014i23mlkdslkf'
if (!Sign || Sign != sysSign) return next(new BizError(ERRORENUM.非法登录, `内部接口非法调用 ${Sign}`));
return next();
}
else {
// let query = req.query || {};
......@@ -82,5 +89,17 @@ export async function authentication(req, res, next) {
}
export async function fileUpAuthentication(req, res, next) {
}
export async function checkInterior(req, res, next) {
if (!req.headers) req.headers = {};
const Sign = req.headers.sign;
let sysSign = 'isdfalfdjasoiufoisjdlnad29230428029014i23mlkdslkf'
if (!Sign || Sign != sysSign) return next(new BizError(ERRORENUM.非法登录, `内部接口非法调用 ${Sign}`));
next();
}
\ No newline at end of file
......@@ -34,25 +34,25 @@ export class httpServer {
// httpServer.use(bodyParser.urlencoded({limit:'5mb', extends:true}));
// 文件下载的授权验证中间件(跳过 OPTIONS 请求)
httpServer.use(FILES_BASE_PATH, (req, res, next) => {
const filePath = path.join(__dirname, '../../files', req.url.replace(FILES_BASE_PATH, ''));
console.log('请求文件路径:', filePath); // 调试日志
console.log('请求方法:', req.method); // 添加日志
if (req.method === 'OPTIONS' || req.method === 'HEAD') {
return next();
}
// httpServer.use(FILES_BASE_PATH, (req, res, next) => {
// const filePath = path.join(__dirname, '../../files', req.url.replace(FILES_BASE_PATH, ''));
// console.log('请求文件路径:', filePath); // 调试日志
// console.log('请求方法:', req.method); // 添加日志
// if (req.method === 'OPTIONS' || req.method === 'HEAD') {
// return next();
// }
const authHeader = req.headers['token'];
console.log('认证token:', authHeader); // 调试日志
if (authHeader === SECRET_TOKEN) {
next();
} else {
res.status(401).json({
code: 401,
message: 'Unauthorized: Missing or invalid Authorization header'
});
}
});
// const authHeader = req.headers['token'];
// console.log('认证token:', authHeader); // 调试日志
// if (authHeader === SECRET_TOKEN) {
// next();
// } else {
// res.status(401).json({
// code: 401,
// message: 'Unauthorized: Missing or invalid Authorization header'
// });
// }
// });
// 设置静态文件服务,只对/yuyi/files路径生效
// httpServer.use(FILES_BASE_PATH, express.static(path.join(__dirname, '../../files')));
......@@ -65,7 +65,7 @@ export class httpServer {
httpServer.use(compression());
httpServer.use(bodyParser.json({limit:"5000kb"}));
httpServer.use(bodyParser.json({limit:"50000kb"}));
routers.setRouter(httpServer);
httpServer.use(httpErrorHandler);
......
......@@ -4,13 +4,19 @@
import asyncHandler = require('express-async-handler');
import { parseFormParam } from '../middleware/fromParam';
import { getFilesId } from '../tools/systemTools';
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
import * as archiver from 'archiver';
const xlsx = require('node-xlsx');
export function setRouter(httpServer){
httpServer.post('/file/xcx/up', parseFormParam, asyncHandler(upFiles));
httpServer.post('/file/applyfor/up', parseFormParam, asyncHandler(upFiles));
httpServer.post('/file/admin/up', parseFormParam, asyncHandler(upFiles));
/**压缩包 */
httpServer.post("/file/admin/zipdownload/consolidated", asyncHandler(downloadConsolidated));
}
async function upFiles(req, res) {
......@@ -28,4 +34,102 @@ async function upFiles(req, res) {
res.success({isSuccess:true, url:`/yuyi/files/${upType}/${fileName}`, fileName});
}
async function downloadConsolidated(req, res) {
let {excelDataList, fileList, zipFileName} = req.body;
//fileList 格式:[ {enterpriseName:"", thisEnterpriseFilesList:[{dirName:"商标", subList:[{fileName:"商标名1", url:"" }] }, {}] }]
//zipFileName 压缩包名称
//excelDataList 格式:{ name:"sheet1", data:[[]]} ];
//创建目录
let thisOptionPath = zipFileName;
await fs.mkdirSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), 'files', 'yuyi', 'files', thisOptionPath));
//写入excel表格
let buff = xlsx.build([excelDataList]);
//这里使用了压缩包的名称做excel表格名称,如果要改的话,在这里把`${thisOptionPath}.xlsx`改了就好了
fs.writeFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), 'files', 'yuyi', 'files', thisOptionPath, `${zipFileName}.xlsx`), buff);
//把文件写入到创建的目录中
for (let i = 0; i < fileList.length; i++) {
let {enterpriseName, thisEnterpriseFilesList } = fileList[i];
await fs.mkdirSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), 'files', 'yuyi', 'files', thisOptionPath, enterpriseName));
for (let k = 0; k < thisEnterpriseFilesList.length; k++) {
let {dirName, subList} = thisEnterpriseFilesList[k];
for (let j =0; j < subList.length; j++) {
let {fileName, url} = subList[j];
//按循环创建目录,例如:商标 租赁合同 ... 方便对应的文件放到对应的目录下
if (!fs.existsSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), 'files', 'yuyi', 'files', thisOptionPath, enterpriseName, dirName))) {
await fs.mkdirSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), 'files', 'yuyi', 'files', thisOptionPath, enterpriseName, dirName));
}
await dwwebFile(url, path.join(__dirname.substring(0,__dirname.indexOf("out")), 'files', 'yuyi', 'files', thisOptionPath, enterpriseName, dirName), fileName);
}
}
}
//把这个目录打包成zip
await createZipArchive(path.join(__dirname.substring(0,__dirname.indexOf("out")), 'files', 'yuyi', 'files', thisOptionPath), path.join(__dirname.substring(0,__dirname.indexOf("out")),'files', 'yuyi', 'files', `${thisOptionPath}.zip`));
res.success({zipName:`${thisOptionPath}.zip`, dirName:`/yuyi/files/${thisOptionPath}.zip`})
}
/**
* 下载url中的文件到checkPath目录
* @param url
* @param checkPath
* @returns
*/
async function dwwebFile(url, checkPath, fileName) {
/** 去url中下载:url如果是http开头的话,下载文件到checkPath中 */
if (url.indexOf("http") > -1) {//非本地文件 去下载
const fetchOptions: any = {
method: 'GET',
timeout: 50000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': '*/*'
}
};
const response = await fetch(url, fetchOptions);
if (!response.ok) {
console.warn(`下载文件失败: ${url}, 状态码: ${response.status}`);
return;
}
const buffer = await response.buffer();
let newPath = path.join(checkPath, `${fileName}.jpg`);
await fs.writeFileSync(newPath, buffer);
} else {//本地文件
//使用fs复制一下文件到目录下就好了
let oldPath = path.join(__dirname.substring(0,__dirname.indexOf("out")), 'files', url);
const ext = path.extname(url);
await fs.copyFileSync(oldPath, path.join(checkPath, `${fileName}${ext}`));
console.log();
}
}
async function createZipArchive(sourceDir: string, outPath: string){
return new Promise((resolve, reject) => {
const output = fs.createWriteStream(outPath);
const archive = archiver('zip', {
zlib: { level: 9 } // 最高压缩级别
});
output.on('close', () => {
console.log(`ZIP文件创建完成: ${outPath}, 大小: ${archive.pointer()} bytes`);
resolve(true);
});
archive.on('error', (err) => {
reject(err);
});
archive.pipe(output);
archive.directory(sourceDir, false);
archive.finalize();
});
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment