delete uploaded file

This commit is contained in:
Takeshi Kimata
2024-03-17 20:29:01 +09:00
parent 1825545bf0
commit 52046992f0
2 changed files with 36 additions and 8 deletions

View File

@@ -20,11 +20,10 @@ module.exports = function (sequelize) {
} }
// delete file from folder // delete file from folder
const uploadDir = path.join(__dirname, "../../public"); const uploadDir = path.join(__dirname, "../../public/uploads");
const url = attachment.path; const url = attachment.path;
const parts = url.split('/'); const fileName = url.substring(url.lastIndexOf("/") + 1);
const fileNameWithFolder = parts.slice(-2).join('/'); const filePath = path.join(uploadDir, fileName);
const filePath = path.join(uploadDir, fileNameWithFolder);
fs.unlink(filePath, (err) => { fs.unlink(filePath, (err) => {
if (err) { if (err) {
console.error('Error deleting file:', err); console.error('Error deleting file:', err);

View File

@@ -1,4 +1,6 @@
"use strict"; "use strict";
const path = require("path");
const fs = require("fs");
module.exports = { module.exports = {
up: async (queryInterface, Sequelize) => { up: async (queryInterface, Sequelize) => {
@@ -179,19 +181,46 @@ module.exports = {
{ {
title: "Selenium logo", title: "Selenium logo",
detail: "", detail: "",
path: "http://localhost:3001/sample/861px-Selenium_Logo.png", path: "http://localhost:3001/uploads/861px-Selenium_Logo.png",
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
}, },
{ {
title: "vitest logo", title: "vitest logo",
detail: "", detail: "",
path: "http://localhost:3001/sample/logo-shadow.svg", path: "http://localhost:3001/uploads/logo-shadow.svg",
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
} },
]); ]);
// copy sample files to uploads folder
const sampleFolderPath = "public/sample";
const uploadsFolderPath = "public/uploads";
const SeleniumLogoFileName = "861px-Selenium_Logo.png";
const vitestLogoFileName = "logo-shadow.svg";
if (!fs.existsSync(uploadsFolderPath)) {
fs.mkdirSync(uploadsFolderPath, { recursive: true });
}
fs.copyFile(
`${sampleFolderPath}/${SeleniumLogoFileName}`,
`${uploadsFolderPath}/${SeleniumLogoFileName}`,
(err) => {
if (err) {
console.log(err);
}
}
);
fs.copyFile(
`${sampleFolderPath}/${vitestLogoFileName}`,
`${uploadsFolderPath}/${vitestLogoFileName}`,
(err) => {
if (err) {
console.log(err);
}
}
);
await queryInterface.bulkInsert("caseAttachments", [ await queryInterface.bulkInsert("caseAttachments", [
{ {
caseId: 1, caseId: 1,
@@ -204,7 +233,7 @@ module.exports = {
attachmentId: 2, attachmentId: 2,
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
} },
]); ]);
}, },