Answer the question
In order to leave comments, you need to log in
How to process files not on the server correctly?
I upload files to the server using multer. The problem is that it requires you to specify exactly the folder where the file will be saved. What if the path to the file must be dynamic, for example, by day of the week?
Storage is set once.
Apparently, through the req parameter in destination, you can pass some parameter, such as "folder", based on it, create a new folder or use an existing one.
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './src/static/uploads/blog');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
})
Answer the question
In order to leave comments, you need to log in
What if the path to the file must be dynamic, for example, by day of the week?
// роутер Express-а ./routes/files
var fs = require('fs');
var express = require('express');
var router = express.Router();
// получаем файлы
var multer = require('multer');
var upload = multer({
dest:'./folder_for_upload_files/'
// прочие опции
}).single("upload");
router.post('/files/upload', function(req, res, next) {
upload(req, res, function (err) {
if (err){
// обработка ошибки
// и завершение обработки запроса res.end() или res.send(...)
return;
}
// если же загрузка произошла успешно, то
// 1. определяем в какую папку и под каким именем переместить файл
// 2. перемещаем файл в нужную папку
// 3. делаем об этом запись в БД или в файлики или кудато еще (в место предназначенное для хранения этой информации)
// 4. завершаем обработки запроса ( res.end() или res.send(...) )
// в помощь:
// req.file.originalname - оригинальное имя файла на компе клиента
// req.file.filename - имя загруженного в "./folder_for_upload_files/" файла
});
});
module.exports = router;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question