关于使用Multer(1.0.6)和Express上传文件

时间:2015-10-17 12:36:17

标签: node.js express multer

我想使用multer从表单中快速上传图像。

我找到一个关于如何使用multer上传文件的post,并触发重命名文件的事件。但是,我发现它只适用于旧版本(multer-0.1.6)

在multer github的最新说明中,我认为我必须使用disk storage engine上传具有新名称的文件,但它不起作用。请给我一些指示,我整天都试过这个功能......

而且,我不确定为什么需要res.status(204).end();?我没有添加此行,当我点击上传按钮时,网页将始终锁定...

的package.json

{
  "name": "FileUpload",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "multer": "^1.0.6",
    "serve-favicon": "~2.3.0"
  }
}

upload.js

var express = require('express');
var multer  = require('multer');
var upload = multer({ storage: storage });

var app = express();

app.post('/uploadImage', upload.single('image'), function (req, res, next) {
    console.log("success");
    console.log(req.file);
    res.status(204).end();
});

app.get('/',function(req,res){
    console.log("It's work");
    res.sendFile(__dirname + "/index.html");
});

var storage = multer.diskStorage({
   destination: function (req, file, cb) {
     console.log("Dest");
     cb(null, 'uploads/')
   },
   filename: function (req, file, cb) {
     cb(null, file.fieldname + '-' + Date.now())
   }
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});

的index.html

<form id        =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/uploadImage"
     method    =  "post"
>
<input type="file" name="image" />
<input type="submit" value="Upload Image" name="submit">
</form>

解决方案 我的代码无法运行的原因是代码的顺序...... 以下顺序是正确的。

var express = require('express');
var multer  = require('multer');

var app = express();

app.get('/',function(req,res){
    console.log("It's work");
    res.sendFile(__dirname + "/index.html");
});

var storage = multer.diskStorage({
   destination: function (req, file, cb) {
     console.log("Dest");
     cb(null, 'uploads/')
   },
   filename: function (req, file, cb) {
     cb(null, file.fieldname + '-' + Date.now())
   }
});

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

app.post('/uploadImage', upload.single('image'), function (req, res, next) {
    console.log("success");
    console.log(req.file);
    res.status(204).end();
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});

1 个答案:

答案 0 :(得分:7)

在GitHub中你可以找到这个例子,对我来说它正在发挥作用:

var express = require('express');
var multer  = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage })

var app = express();

app.post('/uploadImage', upload.single('image'), function (req, res, next) {
    console.log("success");
    console.log(req.file);
    res.status(204).end();
});