2017-04-06 68 views
0

我正在嘗試nodejs第一次。我用python shell來使用它。我試圖將文件從一臺電腦傳輸到另一個使用Post請求從POST請求提取文件nodejs

app.js(服務器PC)

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 

app.post('/mytestapp', function(req, res) { 
    console.log(req) 
    var command = req.body.command; 
    var parameter = req.body.parameter; 
    console.log(command + "|" + parameter) 
    pyshell.send(command + "|" + parameter); 
    res.send("POST Handler for /create") 
}); 

Python文件從(客戶端PC)

f = open(filePath, 'rb') 
try: 
    response = requests.post(serverURL, data={'command':'savefile'}, files={os.path.basename(filePath): f}) 

我送文件使用小提琴手和請求似乎包含在客戶端PC上的文件,但我似乎無法獲得服務器PC上的文件。我如何提取並保存文件?是因爲我缺少標題嗎?我應該使用什麼?謝謝

回答

0

我打算猜測,並說您使用Express基於您的問題的語法。 Express沒有提供開箱即用的文件上傳支持。

您可以使用multerbusboy中間件包添加multipart上傳支持。

它實際上很容易做到這一點,這裏是multer樣本

const express = require('express') 
const bodyParser = require('body-parser') 
const multer = require('multer') 

const server = express() 
const port = process.env.PORT || 1337 

// Create a multer upload directory called 'tmp' within your __dirname 
const upload = multer({dest: 'tmp'}) 

server.use(bodyParser.json()) 
server.use(bodyParser.urlencoded({extended: true})) 

// For this route, use the upload.array() middleware function to 
// parse the multipart upload and add the files to a req.files array 
server.port('/mytestapp', upload.array('files') (req, res) => { 
    // req.files will now contain an array of files uploaded 
    console.log(req.files) 
}) 

server.listen(port,() => { 
    console.log(`Listening on ${port}`) 
}) 
+0

的感謝!但是從客戶端PC(python腳本),上傳文件的代碼是什麼? – golu

+0

@golu不是說你問過關於如何處理上傳文件到Nodejs服務器的問題嗎? – peteb

+0

是的,也許如此。那我還需要另外一個問題嗎? – golu