Node.js 教程第九篇——Express 檔案上傳

DK_Lan發表於2019-02-16

檔案上傳

  • body-parser 並不技術檔案上傳,所以這裡要用到另一個第三方模組 multer
  • 安裝 multer npm install multer
  • 使用前先定義上傳的路徑

單檔案上傳

//引入express模組  
var express = require(`express`);  
//引入multer模組  
var multer = require (`multer`);
var path = require(`path`)  ;
//設定上傳的目錄,  
var upload = multer({ dest:  path.join(__dirname,`temp`)});  
var app = express(); 

app.use(express.static(path.join(__dirname, `/`)));

app.post(`/singleUpload`, upload.single(`avatar`), function (req, res, next) {  
    console.log(req.file);  
    console.log(req.body);  
    res.end("上傳成功");  
});  

app.listen(88)  
<form action="http://localhost:88/singleUpload" method="post" enctype="multipart/form-data">
    <input type="text" name="username" id="">
    <input type="text" name="pwd" id="">
    <input type="file" name="avatar" id="">
    <input type="submit" value="submit">
</form>

多檔案上傳

//注意上傳介面中的 <input type="file" name="photos"/>中的name必須是下面程式碼中指定的名  
app.post(`/mulUpload`, upload.array(`photos`, 12), function (req, res, next) {  
  console.log(req.files);  
  console.log(req.body);  
  res.end(req.file + "<br/><br/>" + req.body);  
}) 

原生js

    <form>
        <input type="text" name="username" id="username">
        <input type="text" name="pwd" id="pwd">
        <input type="file" name="photos" id="photos" multiple>
        <input type="button" value="submit" id="btn_submit">
    </form>
    <script>
        window.onload = function(){
            document.getElementById(`btn_submit`).onclick = function(){
                var myForm = new FormData();    // 建立一個空的FormData物件
                myForm.append("username", document.querySelector(`#username`).value);       // append()方法新增欄位
                myForm.append("pwd", document.querySelector(`#pwd`).value);   // 數字123456立即被轉換成字串“123456”
                
                let files = document.querySelector(`[type=file]`).files;
                for(var i = 0; i < files.length; i++){
                    myForm.append("photos", files[i]);                
                }                

                var xhr = new XMLHttpRequest();
                xhr.open("POST","mulUpload");
                xhr.send(myForm);
            }
        }
    </script>    

jquery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.js"></script>
</head>
<body>
    <form>
        <input type="text" name="username" id="username">
        <input type="text" name="pwd" id="pwd">
        <input type="file" name="photos" id="photos" multiple>
        <input type="button" value="submit" id="btn_submit">
    </form>

    <script>
        $(function(){
            $(`#btn_submit`).click(function(){
                var myForm = new FormData();    // 建立一個空的FormData物件
                myForm.append("username", document.querySelector(`#username`).value);       // append()方法新增欄位
                myForm.append("pwd", document.querySelector(`#pwd`).value);   // 數字123456立即被轉換成字串“123456”
                let files = document.querySelector(`[type=file]`).files;
                for(var i = 0; i < files.length; i++){
                    myForm.append("photos", files[i]);                
                }
                $.ajax({
                    url: `mulUpload`,
                    type: `post`,
                    data: myForm,
                    contentType: false,
                    processData: false,
                    success: function(res){
                        console.log(res)
                    }
                })
            })
        })
    </script>
</body>
</html>

全域性本地儲存

//引入express模組  
var express = require(`express`);  
//引入multer模組  
var multer = require (`multer`);
var path = require(`path`)  ;
var fs = require(`fs`);
//設定上傳的目錄,  
// var upload = multer({ dest:  path.join(__dirname,`temp`)});  

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        var _path = path.join(__dirname, "../uploadFile");
        if(!fs.existsSync(_path)){
            fs.mkdirSync(_path);
        }
        cb(null, _path);    // 儲存的路徑,備註:需要自己建立
    },
    filename: function (req, file, cb) {
        // 將儲存檔名設定為 欄位名 + 時間戳,比如 logo-1478521468943
        cb(null, file.originalname);  
    }
});

// // 通過 storage 選項來對 上傳行為 進行定製化
var upload = multer({ storage: storage })

var app = express(); 

app.use(express.static(path.join(__dirname, `/`)));

app.post(`/singleUpload`, upload.single(`photos`), function (req, res, next) {  
    console.log(req.file);  
    console.log(req.body);  
    res.end("上傳成功");  
});  

app.post(`/mulUpload`, upload.array(`photos`, 12), function (req, res, next) {  
    console.log(req.files);  
    console.log(req.body);  
    res.end("上傳成功");  
})

app.listen(88)

相關文章