2016-11-08 8 views
1

Node.jsサーバーを使用してファイルをアップロードするAPIを作成しようとしています。私はundefined応答を得る。Node.jsにHTMLでファイルをアップロード

私はこのチュートリアルhttps://www.youtube.com/watch?v=UtfZ-5WKpro

のNode.js以下午前:私はundefined応答を得提出クリックした後

var express = require('express'); 

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

app.use(bodyParser.json()); 

app.post("*", function(req, res) { 
    res.end(JSON.stringify(req.files) + "\n"); 
}); 

console.log("Server at 8080"); 
app.listen(8080); 

HTML

<html> 
    <head> 
    <form method="post" 
      enctype="multipart/form-data" 
      action="http://localhost:8080"> 
     <input type="file" name="myimage" /> 
     <input type="submit" name="submit" value="submit"/> 
    </form> 
    </head> 
</html> 

を。

答えて

5
bodyParser.json() 

...ので、あなたはJSON形式のリクエスト

enctype="multipart/form-data" 

ためのパーサを設定している...しかし、あなたはJSON形式の要求を行っていません。

the documentation for body-parserを参照してください:

これは彼らの複雑で、一般的に大規模な性質のためにマルチパートボディを、処理しません。マルチパート本体については、次のモジュールに興味があります。

...候補リストが続きます。

マルチパートリクエストを処理し、現在の選択肢の代わりに使用できるモジュールを選択します。

1

Node/Expressでのファイルアップロードの処理には、this moduleを使用することをお勧めします。

var fileupload = require('fileupload').createFileUpload('/uploadDir').middleware; 

app.post('/upload', fileupload, function(req, res) { 
    // files are now in the req.body object along with other form fields 
    // files also get moved to the uploadDir specified 
}); 

ファイルをアップロードする別の方法

この

ジェイドテンプレート

form.data(action='/user/register', method='post', class="long-fields", enctype='multipart/form-data') 
    input(type="text" name="name") 
    input(name='fileLogo', type='file') 
    input(type="submit" value="Register") 

コントローラ

formidable = require('formidable'); //file upload handling via form 
uuid = require('node-uuid'); //Unique ID 
path = require('path'); //Path compiler 
fs = require('fs'); //FileSystem 

var form = new formidable.IncomingForm(); 
form.keepExtensions = false; 
form.maxFieldsSize = 2 * 1024 * 1024; //2mb 

form.parse(req, function(err, fields, files) { 

    console.log(fields); 
    console.log(files); 

    fs.readFile(files.fileLogo.path, function (err, data) { 
    var pathNew = __dirname + '/../../uploads/' + uuid.v1() + path.extname(files.fileLogo.name); 

    fs.writeFile(pathNew, data, function (err) { 
     console.log('uploaded', pathNew); 
    }); 
    }); 

    res.send(jade.renderFile(settings.pathLess + prefix + '/register.jade', { 
    req: req 
    })); 

}); 
ようなものを使用している可能性
関連する問題