Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

利用multer实现文件上传 #8

Open
izuomeng opened this issue Oct 14, 2017 · 0 comments
Open

利用multer实现文件上传 #8

izuomeng opened this issue Oct 14, 2017 · 0 comments
Labels

Comments

@izuomeng
Copy link
Owner

在学习node时发现书上说body-parser中间件可以解析文件,自己实验了之后发现req.files仍然是undefined,查了一下官方文档才发现,body-parser不提供文件类型的解析:

This does not handle multipart bodies, due to their complex and typically large nature. 
For multipart bodies, you may be interested in the following modules

于是用了推荐的multer中间件,语法也很简单:

var express = require('express');
var app = express();
var multer  = require('multer');
var upload = multer({dest: 'uploads/'});//默认上传路径,根目录下的uploads文件夹
app.post('/upload', upload.single('image'), function(req, res, next) {
	console.log(req.body, req.file);
})

single是最简单的上传单个文件,需要注意的是,single里面的字符串必须要和表单中定义的file字段的名字一样才行,否则会报错,随便上传一张图片,看一下输出结果:

/*
  表单如下(注意必须加上enctype,因为默认是application/x-www-form-urlencoded):
  <form method="post" enctype="multipart/form-data">
        <p><input type="text" name="img_name" placeholder="Name" /></p>
        <p><input type="file" name="image" /></p>
        <p><input type="submit" value="Upload"></p>
    </form>
*/
{ img_name: 'six' } 
{ 
  fieldname: 'image',
  originalname: '六弄咖啡馆.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'uploads/',
  filename: '9c18715d2239f6041c9dbd41fc8c5271',
  path: 'uploads/9c18715d2239f6041c9dbd41fc8c5271',
  size: 1430125 
}

可以看到,对于单个文件,req.file直接等于该文件对象,里面保存了关于文件信息的各种字段。最后会发现上传的文件保存格式是二进制文件,无法直接使用,这时可以用fs.rename方法来重命名文件和文件路径,使其变成可访问的文件

var img = req.file,
      name = img.originalname,
      path = join(__dirname, `/public/images/${name}`);//new path
fs.rename(img.path, path, function(err) {
	if (err) {
		handleError(err);
	}
});

如果要上传多个文件,也是同理,具体参考multer官方文档

@izuomeng izuomeng added the Node label Oct 14, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant