NodeJS上传照片

时间:2015-02-09 23:56:43

标签: node.js express image-uploading

我是节点的新手,我在上传照片时遇到了很多麻烦;

这是我的代码:

 var express = require("express"),
    bodyParser = require('body-parser'),
     app = express();

 app.set('views', __dirname + '/Views');
 app.engine('html', require('ejs').renderFile);
 app.set('view engine', 'ejs');
 app.use(express.bodyParser());
 app.use( bodyParser.json() );       // to support JSON-encoded bodies
 app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
   extended: true
 })); 

 app.use(express.json());       // to support JSON-encoded bodies
 app.use(express.urlencoded());



app.post('/upload',function(request,response){

    response.writeHead(200, "OK", {'Content-Type': 'text/plain'});

    console.log(request.body);

    response.end();
});

这是index.html我的表格:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
    <h1>Test Drive  Upload</h1>
    <form method="post" enctype="multipart/form-data" action="/upload">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="file" name="thumbnail">
    <input type="submit">
    </form>
</body>
</html>

当我尝试上传照片并点击提交时,我会查看我的控制台以查看正文中的内容(我希望对文件提供一些提示!)但是在点击提交后这是控制台

    { username: '', password: '' }

没有任何文件或图像的迹象

我也试过这个:

   console.log(request.files);
   console.log(request.form);

但两者都会在控制台中抛出 undefiend

2 个答案:

答案 0 :(得分:0)

您已设置multipart/form-data用于上传文件,但您启用的中间件均未支持该内容类型。通常,您使用multipartybusboy等中间件来解析多部分请求数据,例如您的图片。

答案 1 :(得分:0)

版本1,不使用正文解析器:

var express = require('express');
var http = require('http');
var app = express();

app.use(express.static('./public'));


app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.multipart({
        uploadDir: './uploads',
        keepExtensions: true
    }));
});


app.use(app.router);

app.get('/upload', function(req, res){
    // Render page with upload form
    res.render('upload');
});

app.post('/upload', function(req, res){
    // Returns json of uploaded file
    res.json(req.files);
});

http.createServer(app).listen(3000, function() {
    console.log('App started');
});

使用正文解析器的第2版:

var express = require('express')

var app = express()
app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/uploads' }))

app.get('/', function(req, res){
  res.send('<form method="post" enctype="multipart/form-data">'
    + '<p>Image: <input type="file" name="image" /></p>'
    + '<p><input type="submit" value="Upload" /></p>'
    + '</form>');
});

app.post('/', function(req, res, next){

    res.send('Uploaded: ' + req.files.image.name)
    return next()

});

app.listen(3000);
console.log('Express app started on port 3000');

这是一个很好的Tutorial | Upload Image using Node.js

快乐帮助!