使用动态文件名(以数字顺序)来表示multer上传文件

时间:2019-04-07 17:18:49

标签: node.js express

我是Node JS的新手,并且想创建一个服务器Rest API,用于以文件名(按数字顺序(例如1、2、3、4))上传图像。

server.js

const storage = multer.diskStorage({
  destination: function (request, file, callback) {
    var newDestination = 'dataset/' + request.body.ktp;
    var stat = null;
    try {
      stat = fs.statSync(newDestination);
    } catch (err) {
      fs.mkdirSync(newDestination);
    }
    if (stat && !stat.isDirectory()) {
      throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"');
    }
    callback(null, newDestination);
  },
  filename(request, file, callback) {
    // const extension = path.extname(file.originalname);
    callback(null, Date.now() + '.jpg');
  }
});
const upload = multer({ storage: storage });

app.use('/images', express.static('dataset'));

app.post('/registrasi', upload.array('photos'), function (req, res) {
  const { ktp, nama, namaPerusahaan, alamat } = req.body;

  const uploadInfo = req.files.map(file => {
    return {
      sourceName: file.originalname,
      newName: file.filename,
      ktp: ktp,
      nama: nama,
      namaPerusahaan: namaPerusahaan,
      alamat: alamat
    };
  });
  res.send(uploadInfo);
});

我的问题是我想从上传的图像创建动态文件名(例如1、2、3、4)。 如果有人知道,请帮助我。任何建议表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:1)

尝试以下操作。

if(!req.headers.index)
   req.headers.index=0
var filename = (req.headers.index++) + path.extname(file.originalname)