大家好我正在使用jade生成html并在页面上显示此表单:
p Upload New Schedule
#uploadNew
form(id = "form1", action="/upload", method="post", enctype="multipart/form-data")
input(type="file", id="control")
br
input(type="submit" value="Upload" name="Submit")
当我选择文件并尝试上传时,连接超时。我究竟做错了什么?我正在使用multer中间件来帮助上传:
回到app.js:
var multer = require('multer');
var upload = multer({dest: './uploads'});
...
app.post('/upload', upload.single('Submit'), function(req, res) {
if (done == true) {
console.log(req.files);
res.end("File uploaded");
}
});
答案 0 :(得分:0)
除了gaurav gupta的回答,当使用multer的upload.single()
函数作为中间件时,您的文件将位于req.file
,而不是req.files
。 req.files
用于upload.array()
或upload.any()
。
var multer = require('multer');
var upload = multer({dest: './uploads'});
app.post('/upload', upload.single('control'), function(req, res) {
console.log(req.file);
res.send("File uploaded");
});
答案 1 :(得分:0)
使用multer上传和检索多个文件(一个二进制文件,一个JSON)的复制粘贴示例...
客户端:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="binaryFileToUpload" id="binaryFileToUpload" >
<input type="file" name="jsonFileToUpload" id="jsonFileToUpload" >
<input type="button" value="Upload" name="submit" onclick="upload()">
</form>
<script>
upload()
{
let fileInput = document.getElementById("file");
var one = fileInput.files[0]; //binary
var two = new Blob([JSON.stringify(this.someRegularObj, null, 2)],
{type : 'application/json'}); //JSON
var url = "http://localhost:4000/upload"; //your URL here
var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert('File(s) uploaded!');
};
xhr.open("POST", url, true);
if (window.FormData) // Chrome
{
var formData = new FormData();
//must match server's router.post('/receiveFiles', upload.array("upload", ...), ...
formData.append("upload", one);
formData.append("upload", two);
xhr.send(formData);
}
}
</script>
服务器端(ES6模块/类):
defineRoutes()
{
let upload = multer({storage: multer.memoryStorage()});
let selector = "upload"; //must match client's formData.append() key!
let numFiles = 2;
router.post('/receiveFiles', upload.array(selector, numFiles),
this.tryExtractFilesFromRequest.bind(this)
);
}
tryExtractFilesFromRequest(req,res,next)
{
if (req.files)
{
let one = req.files[0];
console.log(one); //instance of File, has .buffer, a binary representation
let twoAsJsonString = Buffer.from(req.files[1].buffer, 'binary').toString('utf8');
let two = JSON.parse(twoAsJsonString);
res.end();
}
}