fox1t / fastify-multer

Fastify plugin for handling multipart/form-data
MIT License
89 stars 14 forks source link

dynamic destination. #3

Closed Alexufo closed 4 years ago

Alexufo commented 4 years ago

Hi, I can't get work destination string with Date.now() dynamically. Always return date of started server. In file name Date.now() works good.

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads/'+ Date.now()) // not work
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})
fox1t commented 4 years ago

Thanks for pointing this out. May I ask you publish on GitHub a reproduction repository? So I can clone it and work on a fix on the same environment you have. Thanks!

fox1t commented 4 years ago

I need to specify one important thing: destination is a folder that is created at the server startup and that method isn't called during uploads. If you want to put files in a dynamic folder you can set it as filename and it will join the paths: https://github.com/fox1t/fastify-multer/blob/master/src/storage/disk.ts#L53

so for your specific case just do:

const storage = multer.diskStorage({
  destination: '/tmp/my-uploads/',
  filename: function (req, file, cb) {
    cb(null, `${Date.now()}/${file.fieldname}-${Date.now()}`)
  }
})

Let me know if this fixes your issue.

Alexufo commented 4 years ago

It is by design. Ok. Thank you. :-)

Alexufo commented 4 years ago

by the way.Trick with filename does not work too. We should create path another way

fox1t commented 4 years ago

Hi! It is not a trick, it is the correct way to do it. A filename it is just a path, so you can write relative paths to the upload folder. Can you provide a repro repo so I can check it out?

Alexufo commented 4 years ago

Hello my dear friend! :-)

I did it. But path in filename not created on the fly. I add checking before return file path and all works. (better to use async functions, not existsSync etc)


const dir  = Date.now();
const storage = multer.diskStorage({
  destination: '/tmp/my-uploads/',
  filename: function (req, file, cb) {
    if (!fs.existsSync(dir) {
          fs.mkdirSync(dir, { recursive: true })
    }
    cb(null, `${dir}/${file.fieldname}-${Date.now()}`)
  }
})