I am working on the backend of a MERN app where, using postman, I have to upload jpg/jpeg... files that stores first in a directory "files" in my project and then in the File collection in MongoDB with ID as name ([id].jpg) . I have to use fs.readFile() and fs.writeFile() to do it, but the max result I obtained is "undefined".
The files temporarly stores in a folder on my pc and i don't know how to change this.
Moreover I have to obtain the extension of the file, and they suggested me to use
const array = file.name.split(“.”); const extension = array[array.length - 1].toLowerCase();
THIS IS MY MODEL:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const FileSchema = new Schema({
fileName: {
type: String,
required: true,
},
fileType: {
type: String,
required: true,
},
extension: {
type: String,
required: true,
},
size: {
type: String,
required: true,
},
});
module.exports = File = mongoose.model('file', FileSchema);
THIS IS MY UPLOAD FILE:
const File = require("../../models/File");
const express = require("express");
const formidableMiddleware = require("express-formidable");
const app = express();
app.use(formidableMiddleware());
const fs = require("fs");
module.exports = async (req, res) => {
const test = ({ file } = req.files);
console.log("the files store temporarly here", test["file"]["path"]);
try {
fs.readFile("C:\Users\grazi\AppData\Local\Temp", 'utf-8', (err, data) => {
console.log(data);
});
} catch (e) {
console.log(e);
}
try {
fs.writeFile("C:\Users\grazi\wa\Service-stats2\backend\files", 'C:\Users\grazi\wa\Service-stats2\backend\models\File.js', (err, data) => {
console.log(data);
});
} catch (e) {
console.log(e);
}
};
IF I SEND A REQUEST WITH POSTMAN THIS IS THE OUTPUT OF MY TERMINAL:
the files store temporarly here:
C:\Users\grazi\AppData\Local\Temp\upload_753ecef1d508a15025b20a29e07e65a3
undefined
undefined