ajax2.0、FormData、express拖拽文件上传及进度条Demo
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>文件上传</title> <style> *{ margin: 0; padding: 0; } .box{ width: 300px; height: 200px; border: 1px solid black; background: #eee; position: absolute; top: 50%; left: 50%; margin-left: -150px; margin-top: -100px; line-height: 200px; text-align: center; } </style> </head> <body> user: <input type="text" id="user"><br> pass: <input type="password" id="pass"> <progress max="100" id="prog"></progress> <!--进度条--> <div class="box"> 将文件拖拽至此 </div> <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script> <script> var box = document.querySelector('.box'); box.ondragenter=function(e){ //drag相关拖拽事件 this.innerText = '放手上传' }; box.ondragover = function(e){ e.preventDefault(); //阻止默认事件,不让浏览器打开拖拽的文件 } box.ondrop = function(e){ this.innerText = '将文件拖拽至此'; e.preventDefault(); var fd = new FormData(); fd.set('user',$('#user').val()); fd.set('pass',$('#pass').val()); Array.from(e.dataTransfer.files).forEach((file)=>{
//files是类数组,先转数组,在逐个append进fd fd.append('file',file) }) var xhr = new XMLHttpRequest(); xhr.open('POST','http://127.0.0.1:8080/upload'); xhr.upload.addEventListener('progress',(e)=>{ //要监听xhr.upload的事件就要使用原生的,且在send前绑定事件,即xhr.readyState状态相关
//xhr 本身也可以监听 progress事件,这个事件是监听 请求返回的,存在相同的event--------ajax一般不监听返回进度
var percent = Math.floor(e.loaded /e.total * 100); $('#prog').attr('value',percent) console.log(percent) }) xhr.send(fd) xhr.onreadystatechange = function(){ console.log(xhr.readyState,xhr.status) if(xhr.readyState == 4 && xhr.status == 200){ console.log('ajax done') console.log(xhr.responseText) } } } box.ondragleave = function(){ this.innerText = '将文件拖拽至此'; } </script> </body> </html>
2. server.js
const express = require('express'); const multer = require('multer'); const body_parser = require('body-parser'); const fs = require('fs'); let server = new express(); server.use(body_parser.urlencoded({extended:false})) //使用body-parser中间件 let multerObj = multer({dest:'./upload/'}); //配置multer将上传的文件放到 ./upload server.use(multerObj.any()); //使用multer中间件 server.listen(8080); server.post('/upload',(req,res)=>{ // console.log(req.body); //body-parser 使 req有body属性获取提交的普通数据 // console.log(req.files) //multer 使 req有files属性获取文件 res.end('success') }) server.use(express.static('./www')) //express的静态目录 为 ./www
3. 效果