gpt4 book ai didi

node.js - Nodejs + Expressjs : Pass value in POST with Uploading of file

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:10 25 4
gpt4 key购买 nike

我是 Node 新手。我只想在 POST 请求中传递值,例如上传文件。这是我的示例代码:

 var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });

var multer = require('multer');
var upload = multer({ dest: '/tmp/'});
app.use(express.static('public'));
app.post('/process_post', urlencodedParser, function (req, res) {
console.log(req.files.file.name);

var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'Save successfully',
first_name:req.body.firstname,
last_name:req.body.lastname,
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})

HTML:

 <html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST" enctype="multipart/form-data">
First Name: <input type="text" name="firstname">
<br>
Last Name: <input type="text" name="lastname">
<br>
Picture: <input type="file" name="file" size="50" />
<br>
<input type="submit" value="Submit">
</form>
</body></html>

req.files 始终未定义。提前致谢!

最佳答案

需要multer,但从未配置或使用它。来自文档:

var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})

关于node.js - Nodejs + Expressjs : Pass value in POST with Uploading of file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34624651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com