node上傳圖片第一種方式 1,首先引入模塊 "connect-multiparty": "~1.2.5", 在package.json中添加 "connect-multiparty": "~1.2.5", 然後在命令中切換到項目目錄,使用npm命令:npm installl; 基本配置完成 ind ...
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上傳圖片的方法