簡易檔案上傳網頁 express + multer

使用 express + multer 套件實作檔案上傳

後端程式碼

var express = require('express')
var app = express()
var multer = require('multer')
var storage = multer.diskStorage({
  destination: function(req, file, cb){
    cb(null, './uploads')
  },
  filename: function(req, file, cb){
    cb(null, file.originalname)
  }
})
var upload = multer({ storage: storage })

app.get('/',function(req,res){
  res.sendFile(__dirname + '/index.html');
})

app.post('/', upload.single('upload'), (req, res, next) => {
  res.sendFile(__dirname + '/index.html');
})

app.listen(3000)

前端HTML

<html>
<head>
    <title>Simple Upload Example</title>
</head>
<body>
<form action="/" enctype="multipart/form-data" method="post">
    <input type="file" name="upload" multiple>
    <input type="submit" value="Upload">
</form>
</body>
</html>