multer

μ„€μ •Β·2021λ…„ 1μ›” 9일
0

πŸ’Ύ multer

MulterλŠ” 파일 μ—…λ‘œλ“œλ₯Ό μœ„ν•΄ μ‚¬μš©λ˜λŠ” multipart/form-dataλ₯Ό 닀루기 μœ„ν•œ node.js의 미듀웨어

Installation

$ npm install multer

Usage

  • html

  • enctype="multipart/form-data" μ€‘μš”!
// html
<form action="/profile" method="post" enctype="multipart/form-data">
  <input type="file" name="avatar" />
</form>
  • js

  • single / multiple
// js
const express = require('express')
const app = express()
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })

// single
app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

// multiple
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

// multiple
const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
})

js

  • text μ „μš©
const express = require('express')
const app = express()
const multer  = require('multer')
const upload = multer()
 
app.post('/profile', upload.none(), function (req, res, next) {
  // req.body contains the text fields
})

API

  • multer option

  • DiskStorage

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'νŒŒμΌμ €μž₯ μœ„μΉ˜')
  },
  filename: function(req, file, cb) {
    cb(null, file.filename + '-' + Date.now())
  }
})

const upload = multer({ storage: storage })

Reference

Multer [npm κ³΅μ‹λ¬Έμ„œ]
Multer [ν•œκΈ€νŒ]

0개의 λŒ“κΈ€