formData
XMLHttpRequest Level 2 adds a new interface, FormData. With the FormData object, we can simulate a series of form controls through JavaScript with key-value pairs. We can also asynchronously submit the “form” using the XMLHttpRequest send() method. The big advantage of using FormData over plain Ajax is that you can upload a binary file asynchronously.
FormData use
letFormData = new formData () formData has two main methodssetTo append formData. Set ('a'Formdata.append () formData.append() formData.append()'b'// Set b's part-time to 5setDifference from Append? formData.set('a', 5)
formData.set('a'{a: 6} formData.append() {a: 6} formData.append('b', 5)
formData.append('b'{b: [5, 6]}}Copy the code
Use formData to upload pictures
The client
<body>
<input type="file" id="file" style="display: none;">
<button id="btn">upload</button>
</body>
<script>
let btn = document.querySelector('#btn')
let file = document.querySelector('#file')
btn.onclick = function() {file.click()} // listen for input file change value file.onchange =function (event) {
let file = event.target.files[0]
upload(file)
}
function upload(file) {
let xhr = new XMLHttpRequest()
xhr.open('post'.'/upload'.true)
let formData = new FormData()
formData.set('filename', file)
xhr.send(formData)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
alert('success')
}
}
}
</script>
Copy the code
The server
const express = require('express')
const app = express()
const path = require('path')
const multer = require('multer')
const multerObj = multer({ dest: 'uploads/'}) // Upload middleware app.use(multerobj.any ()) app.get()'/', (req, res, next) => {
res.setHeader('Content-Type'.'text/html')
res.sendFile(path.join(__dirname, 'index.html'))
})
app.post('/upload', (req, res, next) => {
console.log(req.files)
res.send({
'states':'success'
})
})
app.listen(9090, () => {
console.log('server listen 9090')})Copy the code