node上传图片第一种方式
1,首先引入模块 "connect-multiparty": "~1.2.5",
在package.json中添加 "connect-multiparty": "~1.2.5",
然后在命令中切换到项目目录,使用npm命令:npm installl;
基本配置完成
index.html
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<form action="/test" method="post">
姓名: <input type="text" name="name"><br>
年龄: <input type="text" name="age"><br>
<input type="submit" value="提交">
</form>
<br>
<span><a title="上串" href="/upload">上传</a></span>
<span><a href="/uploadtupian" title="上传">上传多个图片例子</a>></span>> </body>
</html>
app.js红色标注部分为上传图片代码
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ejs=require('ejs');
var routes = require('./routes/index');
var users = require('./routes/users');
var upload=require('./routes/upload');
var uploadtupian=require('./routes/uploadtupian');
var test=require('./routes/test');
var multer=require("multer");
var app = express();
var flash=require('connect-flash');
var md5=require('md5');
var fs = require('fs');
var multipart=require('connect-multiparty');
// view engine setup
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.use(flash()); //跨域请求 app.all('*',function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); if (req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
}); app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/*app.use(express.bodyParser({uploadDir:'./public/.images'}));*/ app.use('/', routes);
app.use('/users', users);
app.use('/test', test);
app.use('/up',upload);
app.use('/uploadtupian',uploadtupian); app.post('/upload', multipart(), function(req, res){
console.log(req.body.name);
//get filename
var filename = req.files.files.originalFilename || path.basename(req.files.files.ws.path);
//copy file to a public directory
//修改文件名
console.log(filename);
var newname=56; var targetPath = path.dirname(__filename) + '/public/images/' + filename; //copy file
fs.createReadStream(req.files.files.ws.path).pipe(fs.createWriteStream(targetPath)); var newname=path.dirname(__filename)+'/public/images/'+newname+'.jpg';
filename=fs.rename(targetPath,newname,function(err){
if(err){
console.log('改名失败');
}
else{
console.log("改名成功"); }
});
//return file url
res.json({code: 200, msg: {url: 'http://' + req.headers.host + '/' + newname}}); });
/* app.post('/file-upload', function(req, res) {
console.log(req);
// 获得文件的临时路径
var tmp_path = req.files.thumbnail.path;
// 指定文件上传后的目录 - 示例为"images"目录。
var target_path = './public/images/' + req.files.thumbnail.name;
// 移动文件
fs.rename(tmp_path, target_path, function(err) {
if (err) throw err;
// 删除临时文件夹文件,
fs.unlink(tmp_path, function() {
if (err) throw err;
res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
});
});
});*/
app.use('/upload',function(req,res){ res.render('upload',{
title:"文件上产" });
});
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/*//文件上长
app.use(multer({
dest:'./public/images',
rename:function(fieldname,filename){
return filename;
} }))*/
/// error handlers // development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
} // production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
}); module.exports = app;
upload.html
<!DOCTYPE html>
<html>
<head>
<title><%=title%></title>
</head>
<body>
<form method='post' enctype='multipart/form-data' id = "fromUploadFile"> 姓名: <input type="text" name="name"><br>
<input type="file" name="files" class="from-control"><br> <button class='btn btn-primary' onclick="uploadFile()">上传</button>
</form>
<div class="cow" style="text-align: center">
<img id=imgShow>
<p id="#spanMessage"></p>
</div>
</body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/ipload.js"></script> </html>
ipload.js
function uploadFile(){
var fromData=new FormData($("#fromUploadFile")[0]);
$.ajax({
url: '/uploadhaha',
type: 'post',
data: fromData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data){
if(200 === data.code) {
$("#imgShow").attr('src', data.msg.url);
$("#spanMessage").html("上传成功");
} else {
$("#spanMessage").html("上传失败");
}
console.log('imgUploader upload success, data:', data);
},
error: function(){
$("#spanMessage").html("与服务器通信发生错误");
}
});
}
二.上传多组照片
导入模块 "formidable":"1.1.1"
在package.json中加入 "formidable":"1.1.1";
package.json
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "nodejs ./bin/www"
},
"dependencies": {
"express": "~4.0.0",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"ejs": "~0.8.5",
"multer":"0.1.6",
"connect-flash": "0.1.1",
"md5":"^2.1.0",
"connect-multiparty": "~1.2.5",
"formidable":"1.1.1"
}
}
主要代码
app.use('/', routes);
app.use('/users', users);
app.use('/test', test);
app.use('/up',upload);
app.use('/uploadtupian',uploadtupian);
然后再router文件夹中
新建uploadtupian.js
var express = require('express');
var router = express.Router(); /* GET home page. */
router.get('/', function(req, res) {
res.render('up', { title: '上传多组图片' });
}); module.exports = router;
然后视图文件夹下
新建up.html
<!DOCTYPE html>
<html>
<head>
<title><%=title%></title>
</head>
<body>
'<form enctype="multipart/form-data" method="post" action="/up">'+
'<input type="text" name="name" /> '+
'<input type="text" name="password" /> '+
'<input type="file" name="file1" multiple="multiple" /> '+
'<input type="file" name="file2" multiple="multiple" /> '+
'<input type="submit" name="shangchuan" value="提交">'+
'</form>'
</body> </html>
app.js
中添加app.use('/up',upload);
在router文件夹中添加
upload.js文件
var express =require('express');
var path = require('path');
var router =express.Router();
var formidable=require('formidable');
var fs=require('fs'); router.post('/',function(req,res,next){
console.log(req.body);
var form=new formidable.IncomingForm();
form.uploadDir='/tmp';
form.keepExtensions=true; var targetDir=path.join(__dirname,'../public/upload');
fs.access(targetDir,function(err){ if(err){
fs.mkdirSync(targetDir);
}
_fileParse();
});
function _fileParse(){
form.parse(req,function(err,fields,files){
console.log(fields);
if(err) throw err;
var fileUrl=[];
var errCount=0;
var keys=Object.keys(files);
keys.forEach(function(key){
var filePath=files[key].path;
var fileExt=filePath.substring(filePath.lastIndexOf('.'));
if(('.jpg.jpeg.png.gif').indexOf(fileExt.toLowerCase())==-1){
errCount+=1;
}
else{
var fileName=new Date().getTime()+fileExt;
var targetFile=path.join(targetDir,fileName);
//
fs.renameSync(filePath,targetFile);
fileUrl.push('/upload'+fileName);
} }) res.json({fileUrl:fileUrl,success:keys.length-errCount, error:errCount})
})
} }) module.exports=router;
至此完成两种node上传图片的方法