A
A
Andrew2019-09-07 16:35:12
Node.js
Andrew, 2019-09-07 16:35:12

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);
          }
      })

Am I in the right direction?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-09-07
@AndrewRusinas

What if the path to the file must be dynamic, for example, by day of the week?

When receiving a file, in the multer handler, move the file to the folder you need (and rename if necessary). This can be done either by running the OS command from the node ( *nix , win ), or by means of the node itself
It will look something like this:
// роутер 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 question

Ask a Question

731 491 924 answers to any question