客户端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box { 800px; } .box img { 100%; } .fbar { 800px; height: 20px; border: 1px solid #ccc; border-radius: 5px; overflow: hidden; } .bar { 0%; background-color: blue; text-align: center; line-height: 20px; } </style> </head> <body> <form id="form"> <input type="file" name="" id="file"> <div class="box" id="box"> </div> <div class="fbar" id="fbar"> <div class="bar" id="bar">0%</div> </div> </form> <script> var form = document.getElementById('form') var file = document.getElementById('file') var bar = document.getElementById('bar') var box = document.getElementById("box") file.onchange = function() { var formData = new FormData(); formData.append('attrName', this.files[0]) var xhr = new XMLHttpRequest(); xhr.open('post', 'http://localhost:3001/upload'); xhr.upload.onprogress = function(ev) { var result = ev.loaded / ev.total * 100; result = result.toFixed(2) + '%' bar.innerHTML = result bar.style.width = result } xhr.send(formData); xhr.onload = function() { var response = JSON.parse(xhr.responseText) var img = document.createElement('img') img.src = response.path img.onload = function() { box.appendChild(img) } } } </script> </body> </html>
服务端
app.post('/upload', (req, res) => { const form = new formidable.IncomingForm() form.uploadDir = path.join(__dirname, 'public', 'uploads') form.keepExtensions = true form.parse(req, (err, fields, files) => { res.send({ path: files.attrName.path.split('public')[1] }) }) })