標籤:return color 大小 .post art app 讀取 頁面 進階
npm install express multer --save
var Express = require(‘express‘);var multer = require(‘multer‘);var bodyParser = require(‘body-parser‘);var app = Express();app.use(bodyParser.json());// multer 提供了 storage 這個參數來對資源儲存的路徑、檔案名稱進行個人化。var Storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, "./Images"); }, filename: function (req, file, callback) { callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname); }});//Field name and max count 多個檔案上傳var upload = multer({ storage: Storage }).array("imgUploader", 3); // var upload = multer({ dest: ‘upload/‘ });簡單配置// 也可以寫在post方法中 // app.post(‘/upload-single‘, upload.single(‘imgUploader‘), function(req, res, next){// res.send({ret_code: ‘0‘});// });app.get("/", function (req, res) { res.sendFile(__dirname + "/index.html"); //也可以這樣讀取檔案 // var form = fs.readFileSync(‘./form.html‘, {encoding: ‘utf8‘}); // res.send(form);});app.post("/api/Upload", function (req, res) { upload(req, res, function (err) { if (err) { return res.end("Something went wrong!"); } return res.end("File uploaded sucessfully!."); });});app.listen(2000, function (a) { console.log("Listening to port 2000");});
<form id="frmUploader" enctype="multipart/form-data" action="api/Upload/" method="post"> <input type="file" name="imgUploader" multiple /> <input type="file" name="imgUploader" multiple /> <input type="file" name="imgUploader" multiple /> <input type="submit" name="submit" id="btnSubmit" value="Upload" /></form>
node server
訪問 http://127.0.0.1:2000/ ,選擇檔案,點擊“提交”,done。然後,你就會看到Images目錄下多了個檔案。
- 檔案資訊
console.log(‘檔案類型:%s‘, file.mimetype);console.log(‘原始檔案名:%s‘, file.originalname);console.log(‘檔案大小:%s‘, file.size);console.log(‘檔案儲存路徑:%s‘, file.path);
Nodejs進階:基於express+multer的檔案上傳