node+express上传图片

注意: 别用multer 上传文件了,太坑了,普通文本获取不到,折腾了半天没有解决,最后采用 multiparty 解决了;

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<h2>单图上传</h2>
<input type="file" name="logo">
<input type='text' name='username' value=''/>
<input type ='text' name = 'email' value =''/>
<input type="submit" value="提交">
</form>
</body>
</html>


var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var fs = require('fs');
router.post('/upload',function(req,res,next){
var uploadedPath;
var dstPath;
var form = new multiparty.Form({uploadDir: './public/images'});
form.parse(req, function(err, fields, files){

Object.keys(fields).forEach(function(name) { //文本
console.log('name:' + name+";filed:"+fields[name]);
});


Object.keys(files).forEach(function(name) { //文件
dstPath = 'public/images/'+new Date().getTime()+'-'+files[name][0].originalFilename;
uploadedPath = files[name][0].path
});
fs.rename(uploadedPath, dstPath, function(err) {
if(err){
console.log('rename error: ' + err);
} else {
console.log('rename ok');
}
});

})



})

更过multiparty 参数,请参考https://www.npmjs.com/package/multiparty

原文地址:https://www.cnblogs.com/qiyc/p/8622436.html