2017-04-06 67 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