首页 > 代码库 > multer上传图片

multer上传图片

app.js

var fs = require(‘fs‘);
var express = require(‘express‘);
var multer = require(‘multer‘)

var app = express();
var storage = multer.diskStorage({
	//设置上传后文件路径,uploads文件夹会自动创建。
	destination: function (req, file, cb) {
		cb(null, ‘upload/‘)
	}, 
	//给上传文件重命名,获取添加后缀名
	filename: function (req, file, cb) {
		cb(null,  file.originalname);
     }
 });  


var upload = multer({
	storage: storage
});

// 单图上传
app.post(‘/upload‘, upload.single(‘logo‘), function(req, res, next){
  res.send("上传成功");
});

app.get(‘/form‘, function(req, res, next){
  var form = fs.readFileSync(‘./form.html‘, {encoding: ‘utf8‘});
  res.send(form);
});

app.listen(3000);

  

form.html

<form action="/upload" method="post" enctype="multipart/form-data">
  <h2>单图上传</h2>
  <input type="file" name="logo">
  <input type="submit" value="http://www.mamicode.com/提交">
</form>

  

multer上传图片