Why do I get this error when I tried to import excel file in database. I'm using express-fileupload
Error: Cannot access file \tmp\tmp-1-1705547228039
I check the column and it is the same at my database, so I wonder why im getting this error.
index.js
import express from "express";
import cors from "cors";
import uploadUserLibrary from "./routes/uploadUserLibrary.js";
const app = express();
app.use(express.json());
app.use(cors());
app.use("/api/uploadLibrary",uploadUserLibrary);
app.listen(5000, () => {
console.log(`Connected to the backend on port http://localhost:${5000}`);
});
router.js
import express from "express";
import XLSX from "xlsx";
import * as fs from 'fs';
import fileUpload from "express-fileupload";
import path from "path";
import { connection } from "../database/db.js";
const router = express.Router();
const uploadOpts = {
useTempFiles: true,
tempFileDir: '/tmp/',
};
router.post("/", fileUpload(uploadOpts), async (req, res) => {
try {
const { excel } = req.files;
if (
!excel ||
excel.mimetype !==
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
) {
fs.unlinkSync(excel.tempFilePath);
return res.status(400).json({ msg: "File is Invalid!" });
}
const workbook = XLSX.readFile(excel.tempFilePath);
const sheetName = workbook.SheetNames[0];
const data = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
const successData = [];
const failedData = [];
for (let i = 0; i < data.length; i++) {
const {
date,
fullname,
affectedUser,
eventContext,
component,
description,
origin,
ipAddress,
} = data[i];
const sql =
"insert into userlibrary (date, fullname, affectedUser, eventContext, component, description, origin, ipAddress) values (?,?,?,?,?,?,?,?)";
const [rows, fieds] = await connection.execute(sql, [
date,
fullname,
affectedUser,
eventContext,
component,
description,
origin,
ipAddress,
]);
if(rows.affectedRows){
successData.push(data[i])
}else{
failedData.push(data[i])
}
}
fs.unlinkSync(excel.tempFilePath)
return res.json({msg:'Ok', data: {successData, failedData}})
} catch (err) {
console.log(err);
return res.status(500).json({ success: false, message: err.message });
}
x``;
});
router.get("/", async (req, res) => {
res.send("Hello");
});
export default router;
Addition
I also tried editing the uploadOpts.
const uploadOpts = {
useTempFiles: true,
tempFileDir: path.join(new URL(import.meta.url).pathname, '../../tmp'),
};
But when I do that, I get this error instead.
node:internal/fs/utils:353 throw err; ^
Error: ENOENT: no such file or directory, mkdir '\C:\Users\Student\Desktop\library\api\tmp'
