使用 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();
}
}