html原生上传文件方式1:
<!DOCTYPE html>
<html><head><meta charset="utf-8" /><title>Document</title><script></script></head><body><div>选择文件(可多选):<input type="file" id="f1" multiple /><br /><br /><button type="button" id="btn-submit">上 传</button></div><script>function submitUpload() {//获得文件列表,注意这里不是数组,而是对象var fileList = document.getElementById("f1").files;console.log(document.getElementById("f1"), fileList);if (!fileList.length) {alert("请选择文件");return;}var file = new FormData(); //构造FormData对象// file.append('title', document.getElementById('title').value);//多文件上传需要遍历添加到 fromdata 对象for (var i = 0; i < fileList.length; i++) {file.append("file", fileList[i]); //支持多文件上传}for (var value of file.values()) {console.log(value);}console.log(file);var xhr = new XMLHttpRequest(); //创建对象xhr.open("POST", "https://dcdn-jiazheng.21cs.cn/file/upload");// xhr.setRequestHeader("Content-Type", "multipart/form-data");// xhr.setRequestHeader("Authorization", token);xhr.send(file); //发送时 Content-Type默认就是: multipart/form-data;xhr.onreadystatechange = function () {console.log("state change", xhr.readyState);if (this.readyState == 4 && this.status == 200) {var obj = JSON.parse(xhr.responseText); //返回值console.log(obj);if (obj.data) {alert("上传成功");}}};}//绑定提交事件document.getElementById("btn-submit").addEventListener("click", submitUpload);</script></body>
</html>
html原生上传文件方式2:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><metaname="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/><meta http-equiv="X-UA-Compatible" content="ie=edge" /><title>Document</title><style>#progress {height: 10px;width: 500px;border: 1px solid gold;position: relative;border-radius: 5px;}#progress .progress-item {height: 100%;position: absolute;left: 0;top: 0;background: chartreuse;border-radius: 5px;transition: width 0.3s linear;}</style></head><body>文件上传框<br /><input type="file" id="file" /><br />显示进度条<br /><div id="progress"><div class="progress-item"></div></div>上传成功后的返回内容<br /><span id="callback"></span></body><script>//首先监听input框的变动,选中一个新的文件会触发change事件document.querySelector("#file").addEventListener("change", function () {//获取到选中的文件var file = document.querySelector("#file").files[0];//创建formdata对象var formdata = new FormData();formdata.append("file", file);//创建xhr,使用ajax进行文件上传var xhr = new XMLHttpRequest();xhr.open("post", "https://dcdn-jiazheng.21cs.cn/file/upload");//回调xhr.onreadystatechange = function () {if (xhr.readyState == 4 && xhr.status == 200) {document.querySelector("#callback").innerText = xhr.responseText;}};//获取上传的进度xhr.upload.onprogress = function (event) {if (event.lengthComputable) {var percent = (event.loaded / event.total) * 100;document.querySelector("#progress .progress-item").style.width =percent + "%";}};//将formdata上传xhr.send(formdata);});</script>
</html>
其他好的上传组件