bodyParser is used to parse the content in the body requested by the client, and internally uses JSON encoding processing, url encoding processing and file upload processing.
Here is an example of file upload.
Create a 1.html page
The code copy is as follows:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Upload files to server</title>
<script type="text/javascript">
function uploadFile(){
var formData=new FormData();
var files=document.getElementById("files").files;
var file=files[0];
formData.append("myfile",file);
var xhr=new XMLHttpRequest();
xhr.open("post","index.html",true);
xhr.onload= function (e) {
if(this.status==200)
document.getElementById("result").innerHTML=this.response;
};
xhr.send(formData);
}
</script>
</head>
<body>
Please select a file: <input type="file" id="files" name="file" />
<input type="button" value="upload file" onclick="uploadFile();" />
<div id="result"></div>
</body>
</html>
The above XMLHttpRequest object and FormData object are not explained in detail. Use these two objects to upload the files selected by the user to the server.
After using the app.use(express.bodyParser()) middleware on the server side, the http.IncomingMessage, which represents the client request, that is, the res object has a files property.
Server.js side code:
The code copy is as follows:
var express=require("express");
var fs=require("fs");
var app=express();
app.use(express.bodyParser());
app.get("/index.html", function (req,res) {
res.sendfile(__dirname+"/1.html");
});
app.post("/index.html", function (req,res) {
var file=req.files.myfile;
fs.readFile(file.path, function (err,data) {
if(err) res.send("Read file operation failed");
else{
fs.writeFile(file.name,data, function (err) {
if(err) res.send("Write the file operation failed.");
else res.send("File upload successfully");
})
}
});
});
app.listen(1337,"127.0.0.1", function () {
console.log("Start listening");
});
After starting the server, run the browser:
Select a file:
The word upload success appears on the browser.
There are also files we uploaded on the server side.
After clicking upload:
In addition, bodyParse can accept json data submitted by the client ajax and the processing of url.