Node.js express使用Multer實現文件上傳
html部分html
<div> <h3>文件上傳:</h3> 選擇一個文件上傳: <br/> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="content"/> <br/> <input type="submit" value="上傳文件"/> </form> </div>
Node.js部分
安裝multer:npm install multer --savenode
var express = require('express'); var app = express(); var fs = require('fs'); var multer = require('multer'); var upload = multer({dest: 'uploadFile/'}); //文件上傳 app.post('/upload', upload.any(), function (req, res, next) { console.log(req.files[0]); // 上傳的文件信息 var newFile = "./uploadFile/" + req.files[0].originalname; fs.readFile(req.files[0].path, function (err, data) { fs.writeFile(newFile, data, function (err) { if (err) { console.log("錯誤:", err) } else { let response = { message: '上傳成功', filename: req.files[0].originalname }; res.json(response); } }); }) }) //圖片加載,存儲在uploadFile下的全部圖片 app.get('/uploadFile/*', function (req, res) { res.sendFile( __dirname + "/" + req.url ); })
github地址:https://github.com/Rossy11/no...git