HTML5技术

Nodejs 传图片的两种方式 - 菜鸟的进击

字号+ 作者:H5之家 来源:H5之家 2017-05-13 10:03 我要评论( )

node上传图片第一种方式 1,首先引入模块"connect-multiparty": "~1.2.5", 在package.json中添加"connect-multiparty": "~1.2.5", 然后在命令中切换到项目目录,使用npm命令:npm installl; 基本配置完成 index.html !DOCTYPE htmlhtml headtitle%= title %/tit

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 href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> <form action="/test" method="post"> 姓名: <input type="text"><br> 年龄: <input type="text"><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('http://www.cnblogs.com/', 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 + 'http://www.cnblogs.com/' + 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

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • NodeJS+MongoDB+AngularJS+Bootstrap书店示例 - Market/Relay

    NodeJS+MongoDB+AngularJS+Bootstrap书店示例 - Market/Relay

    2017-04-14 15:00

  • 浓缩的才是精华:浅析GIF格式图片的存储和压缩 - 腾讯云技术社区

    浓缩的才是精华:浅析GIF格式图片的存储和压缩 - 腾讯云技术社区

    2017-04-07 15:08

  • HTML5本地图片裁剪并上传 - QxQstar

    HTML5本地图片裁剪并上传 - QxQstar

    2017-03-25 14:00

  • 图片展示丨标签 - xiaohaimiansBlog

    图片展示丨标签 - xiaohaimiansBlog

    2017-03-08 17:00

网友点评