2017-01-23 18 views
0

ファイルをアップロードできるノードサーバーを作成してから、ノードも使用しているストレージサーバーに送信します。要求モジュール経由のノードJSファイル転送

var formData = { 
    my_field: 'my_value', 
    my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), 
}; 

request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) { 
    if (err) { 
    return console.error('upload failed:', err); 
    } 
    console.log('Upload successful! Server responded with:', body); 
}); 

私の問題は、私は、ストレージサーバ上のファイルの書き込みしようとすると、それはコンテンツのテキストファイルを作成することです[オブジェクト: は私がフォームデータモジュールページに記載、この方法を使用していますこれを行うにはオブジェクト]。ここで

は私のコードです:

main.js

var form = new formData(); 
form = { 
     'oldFileName': oldName, 
     'newFileName': newName, 
     'file': fs.createReadStream(FILEPATH), 
    }; 

    request.post({url:'http://127.0.0.1:9001/upload', form: form}, function(err, httpResponse, body) { 
     if (err) { 
      return console.error('upload failed:', err); 
     } 
    }); 

storage.js

app.post('/upload', function(req,res){ 
    //Filenames are displayed without problem 
    console.log(req.body.newFileName); 
    console.log(req.body.oldFileName); 

    fs.writeFile('./testing/' + req.body.newFileName, req.body.file, function(err) { 
    if(err) { 
     return console.log(err); 
    } 
}) 

私は本当に何かを明らかに欠けていると確信しているが、私はカントに思えますそれを働かせる。

+0

'storage.js'で' multipart/form-data'を受け入れるには 'multer'やそれに類するライブラリを使う必要があると思います。 –

+0

私はそれを試しました(申し訳ありませんでした)が、' multer'は表示されませんでした構築されたフォームのファイルを認識するために –

答えて

0

あなたはapplication/x-www-form-urlencoded代わりのmultipart/form-dataに内容を変更requestformオプションでformDataを渡しています。

app.js

var form = { 
    'oldFileName': oldName, 
    'newFileName': newName, 
    'file': fs.createReadStream(FILEPATH), 
}; 

request.post({url:'http://127.0.0.1:9001/upload', formData: form}, function(err, httpResponse, body) { 
    if (err) { 
     return console.error('upload failed:', err); 
    } 
}); 

はまた、multipart/form-dataを解析するために、あなたはbody-parserが、その場合には動作しません、multerまたは類似のライブラリを使用する必要があります。ファイル保存のためのコードstorage.jsを見つけてください。

storage.js

var multer = require('multer') 
    var upload = multer({ 
    storage: multer.diskStorage({ 
     destination: function (req, file, cb) { 
      cb(null, './testing/'); 
     }, 
     filename: function (req, file, cb) { 
      cb(null, req.body.newFileName); 
     } 
    }) 
    }).single('file'); 

app.post('/upload', function(req, res, next){ 
    upload(req, res, function (err) { 
     if(err){ 
      return res.send(err); 
     } else{ 
      return res.send("Upload successfully"); 
     } 
    }); 
}); 

は、それはあなたのお役に立てば幸いです。

+0

それはそれを解決しました、ありがとう! –

関連する問題