이 포스팅에선 postman을 이용하여 업로드를 진행할 것이다. 추후에 안드로이드 어플을 통해서 업로드 Client 부분을 작성할 예정이며 작성하면 이 글을 수정하여 링크를 달아놓을 예정이다.

 

우선 파일을 업로드하여 서버 upload라는 폴더 안에 저장할 것이고, DB에 파일에 대한 정보를 넣을 생각이다. 이 이유는 맨 아래에 남겨놨다.

 

우선 NPM 에서 사용하는 기본 예제다.

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })
 
var app = express()
 
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
})
 
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
})
 
var 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
})

코드에서 보면 알 수 있듯이 upload할 때 속성이 다르다. 

.single(fieldname)

이름을 가진 단일 파일을 허용합니다 fieldname. 단일 파일은 req.file. 로 사용하면 된다.

.array(fieldname[, maxCount])

이름이 모두 인 파일 배열을 허용합니다 fieldname. 둘 이상의 maxCount파일이 업로드 되면 선택적으로 오류가 발생합니다 . 파일 배열은 req.files. 로 사용하면 된다.

.fields(fields)

fields 파라미터로 넘어오는 것들을 배열 형태로 저장된다. 파일은 req.files로 사용하면 된다.

 

 

 

NPM에 나와있는 각 파일 정보다.

multer(opts)

업로드된 파일을 Multer에게 어디로 업로드할 지 알려주며 옵션 객체를 하지않았다면 메모리에 저장된다. 보통은 dest 옵션으로 파일 저장 위치를 지정하는데 더 자세하게 제어하고 싶으면 storage를 사용하면 된다.

var  upload  = multer ( {  dest : ' uploads / ' } ) 

 

storage

DiskStorage

말 그대로 로컬 디스크에 저장한다는 의미이며 두 가지 옵션을 사용할 수 있다. 

1. destnation : 파일의 목적지 즉 경로를 설정 할 수 있다.

2. filename : 파일 이름을 설정 할 수 있다. 아래 코드에서 보면 알 수 있듯이 Date.now()가 들어 갔는데 타임스태프를 넣은 이유가 파일 이름이 겹칠 수 있기 때문이라고 생각해두면 될 것 같다.

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

 

MemoryStorage

메모리 스토리지 엔진은 파일을 메모리에 Buffer개체 로 저장 합니다. 옵션이 없습니다.

var storage = multer.memoryStorage()
var upload = multer({ storage: storage })

 

 

파일 정보를 DB에 저장해둬야 할 필요가 있다. 왜냐면 파일을 다운 받을 경우 자신이 업로드한 파일을 정확하게 받을 수 있다. 그리고 파일 이름은 한글로 넣을 경우 깨지는 경우가 발생했다. UTF-8 등 ... 인코딩 많은걸 해봤지만 안됐다. 나중에 듣기론 이런 경우가 많아 파일 오리지널 이름을 같이 업로드하여 DB에 넣어둔 뒤 다운로드 할 시 DB에서 파일 이름을 꺼내와 다시 붙여주는 걸로 알고 있다. 물론 파일 리스트 조회 할 시도 DB에서 파일 오리지널 이름을 가져와 Client로 넘겨준다.

+ Recent posts