新建文件夹demo
文件夹目录打开cmd
npm install express multer multer --save
手动创建app.js和from.html
app.js
var fs = require('fs');
var express = require('express');
var multer = require('multer');
var path = require('path');
var app = express();
var upload = multer({ dest: 'upload/' });
// 单图上传
app.post('/upload', upload.single('logo'), function(req, res, next){
var file = req.file;//req.file文件包含所有上传图片的所有信息可在api中查看
//文件重命名
var oldfliepath = path.join(__dirname,"upload",file.filename)
var newfilepath = path.join(__dirname,"upload",file.originalname)
fs.rename(oldfliepath,newfilepath,function(err){
if (err) throw err;
fs.stat(newfilepath, function (err, stats) {
if (err) throw err;
// console.log('stats: ' + JSON.stringify(stats));
console.log("文件迁移成功")
});
});
res.send({ret_code: '0'});
});
app.get('/form', function(req, res, next){
var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
res.send(form);
});
app.listen(3000);
form
<!DOCTYPE html>
<html>
<head>
<title>图片上传页面</title>
<meta charset="utf-8">
</head>
<body>
<h1>Logo上传</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<h2>图片上传</h2>
<input type="file" name="logo">
<input type="file" name="logo">
<input type="submit" value="提交">
</form>
</body>
</html>