Search code examples
node.jsvue.jsmulter

No folder is being created upon uploading of files


I am trying to upload pdf/xls/xlsx on the file server but whenever I try to send the file on my back end using FormData, no folder is being created and the file isn't uploaded either.

Here is my code on the front end (Vue):

let toSubmit = {
    document_title: this.document_title.toUpperCase(),
    added_by: this.userInfo.employeeCode,
    FileName: `${this.document_title.replace(/ +/g, "_").toUpperCase()}.${this.$refs.files.files[0].name.split(".").pop().toLowerCase()}`
}

const formData = new FormData

formData.append("toSubmit", JSON.stringify(toSubmit))

_.forEach(this.uploadFiles, file=>{
    formData.append("files", file)
})

const url = `${this.api}add/template/document`
axios.post(url, formData, {
    headers: {
        'Content-Type': 'multipart/form-data',
        dataType: 'json',
    }
}).then(res=>{
    console.log('document template', res.data)
})

And on my back-end, I used multer for uploading the file but I have no idea if the problem lies on multer itself or if I have something missing in my code. Anyway, this is my code on the back end (Node):

API

router.post("/add/template/document", uploadTemplate.array("files"), (req, res)=>{
  let myData = JSON.parse(req.body.toSubmit)
  res.send(myData)
})

Uploading

const uploadTemplate = multer({storage: storageTemplate});
const storageTemplate = multer.diskStorage({
  destination: (req, file, cb) => {
    var dir = `./uploads/DocumentTemplates/`;
    if (!fs.existsSync(dir)){
      fs.mkdirSync(dir);
    }
    cb(null, dir);
  },
  filename: function(req, file, cb){
    let myData = JSON.parse(req.body.toRequest);
    let fileName = myData.FileName
    let new_filename = `${fileName}`
    cb(
      null,
      new_filename
    )
  }
})

I still can't figure out why no folder is being created. Am I missing something?


Solution

  • you're creating a subfolder without recursive flag, that's why the folder is not created

    also, there is no body in multer middleware, only file, so you cannot send custom data to file like that, you need to change upload middleware

    1. to create subfolders, add this flag:
    fs.mkdirSync(dir, {recursive: true});
    
    1. there is no body in multer, use file (you can add mimetype validation, check that only certain types are uploaded):
      filename: function(req, file, cb){
        
        console.log('file', file);
    
        // validate expected file against file.mimetype
        // if it fails, return error: cb(yourErrorMessage, null);
    
        cb(
          null,
          file.originalname // handle on front-end
        )
      }
    

    and on the frontend:

    formData.append("files", file, 'filename goes here');