如果前端上传的文件是zip,后端要如何解压处理呢?
以nestjs为例。首先是接收文件。
Body是无法接收到file的,我们需要借助UseInterceptors修饰器,并使用UploadedFile接收数据。
然后是解压缩,我们需要借助compressing这个包。
注意,如果压缩包里的文件名带中文,需要增加这个选项,否则会出现乱码。
compressing.zip.uncompress(path, fllepath, { zipFileNameEncoding: 'GBK' })
import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { handlecatalogue, handleContent, fsWrite } from './transform';
let path = require('path');
let fs = require('fs');
const compressing = require('compressing');
@Controller('wordtohtml')
export class WordtohtmlController {
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
async uploadFile(@UploadedFile() file): Promise<any> {
let basepath = path.resolve(`public/handbook/`);
let filepath = path.resolve(`public/handbook/pages/`);
let filename = file.originalname.replace(/\.zip$/, '');
let res = await fsWrite(filepath + '/' + `${file.originalname}`, file.buffer);
if (res === 'ok') {
let result = await this.unzip(filepath + '/' + `${file.originalname}`, filepath);
if (result === 'ok') {
//解压成功后,生成文件
handlecatalogue(filepath + '/' + filename + '.htm', basepath + '/' + 'index.html');
handleContent(filepath + '/' + filename + '.htm', filepath + '/' + 'book.html');
}
return { Success: true, Message: '处理成功' }
} else {
return { Success: false, Message: '处理失败' }
}
}
//解压缩
unzip(path, fllepath) {
return new Promise((resolve, reject) => {
compressing.zip.uncompress(path, fllepath, { zipFileNameEncoding: 'GBK' })
.then(() => {
resolve('ok');
})
.catch(err => {
reject(err);
});
});
}
//删除目录
delDir(path) {
let files = [];
if (fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach((file, index) => {
let curPath = path + "/" + file;
if (fs.statSync(curPath).isDirectory()) {
this.delDir(curPath); //递归删除文件夹
} else {
fs.unlinkSync(curPath); //删除文件
}
});
// fs.rmdirSync(path);
}
}
}
网友评论