问题描述
我第一次尝试使用nodejs.我在python shell中使用它.我正在尝试使用发布请求将文件从一台PC传输到另一台PC
I am trying nodejs for the first time. I am using it with python shell. I am trying to transfer a file from one PC to another using Post request
app.js(服务器PC)
app.js (Server 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)发送文件
python file send file from (Client PC)
f = open(filePath, 'rb')
try:
response = requests.post(serverURL, data={'command':'savefile'}, files={os.path.basename(filePath): f})
我使用提琴手,请求似乎包含客户端PC上的文件,但似乎无法在服务器PC上获取该文件.如何解压缩并保存文件?是因为我缺少标题吗?我该怎么用?谢谢
I use fiddler and the request seems to contain the file on Client PC, but I can't seem to get the file on Server PC. How can I extract and save the file? Is it because I am missing headers? what should I use? thanks
推荐答案
我要猜测并说您正在使用基于问题语法的Express. Express不附带对文件上传的开箱即用支持.
I'm going to guess and say you're using Express based on the syntax in your question. Express doesn't ship with out of the box support for file uploading.
您可以使用 multer
或 busboy
中间件软件包,以添加multipart
上传支持.
You can use the multer
or busboy
middleware packages to add multipart
upload support.
实际上很容易做到,这是一个带研磨器的样品
Its actually pretty easy to do this, here is a sample with 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}`)
})
这篇关于从POST请求Node.js中提取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!