From f89bb52fe5a2823ac9dc48afaf7f471402305d8c Mon Sep 17 00:00:00 2001 From: tnud0 <2001040219@s.hanu.edu.vn> Date: Wed, 17 May 2023 18:03:07 +0700 Subject: [PATCH] fix download file error and delete zip file after downloading --- public/15/name name/file.txt | 0 public/15/namename/file.txt | 0 .../download/15/123353222-1684321000419.zip | Bin 0 -> 150 bytes src/api/controllers/v1/path.controller.js | 63 +++++++++++++++--- src/api/controllers/v1/staff.controller.js | 4 +- src/api/controllers/v1/user.controller.js | 44 ++++++++---- src/api/middlewares/path.middleware.js | 14 ++++ src/api/validations/v1/staff.validation.js | 4 +- .../services/adapters/upload-adapter.js | 5 ++ src/config/locales/en.json | 9 ++- 10 files changed, 114 insertions(+), 29 deletions(-) create mode 100644 public/15/name name/file.txt create mode 100644 public/15/namename/file.txt create mode 100644 public/download/15/123353222-1684321000419.zip create mode 100644 src/api/middlewares/path.middleware.js diff --git a/public/15/name name/file.txt b/public/15/name name/file.txt new file mode 100644 index 0000000..e69de29 diff --git a/public/15/namename/file.txt b/public/15/namename/file.txt new file mode 100644 index 0000000..e69de29 diff --git a/public/download/15/123353222-1684321000419.zip b/public/download/15/123353222-1684321000419.zip new file mode 100644 index 0000000000000000000000000000000000000000..d9e5ddcbc59cda2fa4b55991bfac6f6124da05e2 GIT binary patch literal 150 zcmWIWW@Zs#-~htD;EiDnNI($C&P&Wq1!4WP%$!ucl8O>$h5&DN4v;D)sL}v$MkZZm jR3l(=AR{0^fni%Ch=pNbfHx}}NP-av?SZr-h{FH?q}CQ0 literal 0 HcmV?d00001 diff --git a/src/api/controllers/v1/path.controller.js b/src/api/controllers/v1/path.controller.js index 5a0ad0d..b3c9a57 100644 --- a/src/api/controllers/v1/path.controller.js +++ b/src/api/controllers/v1/path.controller.js @@ -12,6 +12,8 @@ import { storage as storageConfig } from '../../../config/vars'; import uploadAdapter from '../../../common/services/adapters/upload-adapter'; +import { cloneDeep, forEach } from 'lodash'; + /** * get file and folder @@ -23,12 +25,11 @@ exports.get = (req, res, next) => { const user = req.user; let path = `${storageConfig.uri}/${user.id}`; - // let path = storageConfig.uri; if (req.body.path) { path += req.body.path; } + // console.log(path); const listFile = []; - fs.readdir(path, (err, files) => { if (files && files.length > 0) { files.forEach((item) => { @@ -44,6 +45,24 @@ exports.get = (req, res, next) => { data: listFile }); }); + // test local + // fs.readdir(path, (err, files) => { + // if (files && files.length > 0) { + // files.forEach((item) => { + // listFile.push({ + // name: item, + // path: `${storageConfig.uri}/${user.id}${req.body.path}/${item}`, + // isFolder: fs.lstatSync(`${storageConfig.uri}/${user.id}/${req.body.path}/${item}`).isDirectory() + // }); + // }); + // } + // return res.json({ + // code: 0, + // data: listFile + // }); + // }); + + return null; /** resize image uploaded */ } catch (ex) { @@ -58,19 +77,18 @@ exports.get = (req, res, next) => { */ exports.create = (req, res, next) => { const user = req.user; - let dir = `${user.id}`; - console.log(dir); + const name_folder = cloneDeep(req.body.name).trim(); if (req.body.path) { dir += req.body.path; } if (req.body.name) { - dir += `/${req.body.name}`; + dir += `/${name_folder}`; } if (!fs.existsSync(dir)) { uploadAdapter.createFolder({ path: dir }); } - return res.json({ code: 0, message: 'success' }); + return res.json({ code: 0, message: 'success'}); }; /** @@ -123,16 +141,24 @@ exports.download = (req, res, next) => { try { const user = req.user; const namefile = `${user.name}-${Date.now()}.zip`; - const dir = `${storageConfig.uri}/${user.id}/${namefile}`; + const dir = `${storageConfig.uri}/download/${user.id}/${namefile}`; + const folder = `${storageConfig.uri}/download/${user.id}`; + + deleteFolderRecursive(folder); const output = fs.createWriteStream(dir); const archive = archiver('zip', { zlib: { level: 9 } // Sets the compression level. }); + archive.pipe(output); if (req.body.data) { req.body.data.forEach((e) => { - const path = e.path.replace(cdnConfig.uri, storageConfig.uri).replace(/ /g, '%20'); + // const path = e.path.replace(cdnConfig.uri, storageConfig.uri).replace(/ /g, '%20'); + const path = e.path.replace(cdnConfig.uri, storageConfig.uri); + // const download = path.split("/"); + // download.splice( download.indexOf(`${user.id}`), 0, "download"); + // const final_path = download.join("/"); if (e.isFolder) { archive.directory(path, e.name); } else { @@ -141,7 +167,6 @@ exports.download = (req, res, next) => { }); } archive.finalize(); - return res.json({ code: 0, data: { @@ -193,4 +218,22 @@ exports.deleteMultiple = (req, res, next) => { } catch (ex) { return ErrorHandel(ex, req, res, next); } -}; \ No newline at end of file +}; + + +function deleteFolderRecursive(folderPath) { + let files = []; + if (fs.existsSync(folderPath)) { + files = fs.readdirSync(folderPath); + files.forEach((file) => { + const currentPath = path.join(folderPath, file); + if (fs.lstatSync(currentPath).isDirectory()) { + deleteFolderRecursive(currentPath); + } else { + fs.unlinkSync(currentPath); + console.log('Deleted file:', currentPath); + } + }); + + } + } diff --git a/src/api/controllers/v1/staff.controller.js b/src/api/controllers/v1/staff.controller.js index 4a31b3e..c4f9f30 100644 --- a/src/api/controllers/v1/staff.controller.js +++ b/src/api/controllers/v1/staff.controller.js @@ -84,7 +84,7 @@ exports.get = async (req, res, next) => res.json({ data: User.transform(req.loca */ exports.update = async (req, res, next) => { const { user } = req.locals; - if (user.service !== "service") { + if (user.service !== "staff") { return res.status(404).json({ code: 404, message : messages.NOT_FOUND @@ -117,7 +117,7 @@ exports.update = async (req, res, next) => { */ exports.delete = async (req, res, next) => { const { user } = req.locals; - if (user.service !== "service") { + if (user.service !== "staff") { return res.status(404).json({ code: 404, message : messages.NOT_FOUND diff --git a/src/api/controllers/v1/user.controller.js b/src/api/controllers/v1/user.controller.js index 7eedf36..99af8e9 100644 --- a/src/api/controllers/v1/user.controller.js +++ b/src/api/controllers/v1/user.controller.js @@ -43,21 +43,37 @@ exports.create = async (req, res, next) => { exports.list = async (req, res, next) => { req.query.services = User.Services.USER; // console.log(req.query.services); - User.list( { - service : "user", - is_active: true - } - ).then(result => { - res.json({ - code: 0, - count: req.totalRecords, - data: result.map( - x => User.transform(x) - ) + // User.list( { + // service : "user", + // is_active: true + // } + // ).then(result => { + // res.json({ + // code: 0, + // count: req.totalRecords, + // data: result.map( + // x => User.transform(x) + // ) + // }); + // }).catch(ex => { + // ErrorHandler(ex, req, res, next); + // }); + + + return User.findAll({ + where : { + service : "user", + is_active: true + } + }).then(result => { + res.json({ + code: 0, + count: req.totalRecords, + data: result + }); + }).catch(ex => { + ErrorHandler(ex, req, res, next); }); - }).catch(ex => { - ErrorHandler(ex, req, res, next); - }); }; /** diff --git a/src/api/middlewares/path.middleware.js b/src/api/middlewares/path.middleware.js new file mode 100644 index 0000000..fcb1cfb --- /dev/null +++ b/src/api/middlewares/path.middleware.js @@ -0,0 +1,14 @@ +import { handler as ErrorHandler } from './errors'; +import fs from 'fs'; +import archiver from 'archiver'; +import multer from 'multer'; +import path from 'path'; +import { handler as ErrorHandel } from '../../middlewares/errors'; +// import ApiException from '../../../common/utils/APIException'; +import { + + cdn as cdnConfig, + storage as storageConfig +} from '../../../config/vars'; +import uploadAdapter from '../../../common/services/adapters/upload-adapter'; + diff --git a/src/api/validations/v1/staff.validation.js b/src/api/validations/v1/staff.validation.js index 833f095..2d624c6 100644 --- a/src/api/validations/v1/staff.validation.js +++ b/src/api/validations/v1/staff.validation.js @@ -55,8 +55,8 @@ module.exports = { .max(255) .required(), phone: Joi.string() - .max(155) - .required(), + .max(155), + // .required(), email: Joi.string() .allow(null, ''), gender: Joi.string() diff --git a/src/common/services/adapters/upload-adapter.js b/src/common/services/adapters/upload-adapter.js index e860f8d..f59892c 100644 --- a/src/common/services/adapters/upload-adapter.js +++ b/src/common/services/adapters/upload-adapter.js @@ -1,6 +1,8 @@ import multer from 'multer'; // import moment from 'moment-timezone'; import { storage as storageConfig } from '../../../config/vars'; +import { forIn } from 'lodash'; +import { equal } from 'joi'; /** storage will create folder when new date */ // const date = new Date(); @@ -36,6 +38,8 @@ const createFolder = ({ path }) => { try { console.log(`${filePath}/${path}`); multer({ dest: `${filePath}/${path}` }); + + // multer({ dest: `${filePath}/images/games` }); // multer({ dest: `${filePath}/images/stories` }); // multer({ dest: `${filePath}/images/chapters` }); @@ -48,6 +52,7 @@ const createFolder = ({ path }) => { // multer({ dest: `${filePath}/images/banners` }); // multer({ dest: `${filePath}/images/categories` }); // multer({ dest: `${filePath}/images/upload/default` }); + // console.log(multer); return true; } catch (ex) { return false; diff --git a/src/config/locales/en.json b/src/config/locales/en.json index 8592bdb..5d6d879 100644 --- a/src/config/locales/en.json +++ b/src/config/locales/en.json @@ -28,5 +28,12 @@ "log is not defined": "log is not defined", "connect ETIMEDOUT 113.177.27.200:5432": "connect ETIMEDOUT 113.177.27.200:5432", "Validation error: Validation isEmail on email failed": "Validation error: Validation isEmail on email failed", - "WHERE parameter \"id\" has invalid \"undefined\" value": "WHERE parameter \"id\" has invalid \"undefined\" value" + "WHERE parameter \"id\" has invalid \"undefined\" value": "WHERE parameter \"id\" has invalid \"undefined\" value", + "blank is not defined": "blank is not defined", + "equal is not defined": "equal is not defined", + "isEqual is not defined": "isEqual is not defined", + "_ is not defined": "_ is not defined", + "Cannot access 'splited_dir' before initialization": "Cannot access 'splited_dir' before initialization", + "main_dir is not defined": "main_dir is not defined", + "Cannot read properties of undefined (reading 'trim')": "Cannot read properties of undefined (reading 'trim')" } \ No newline at end of file