流程:
1.** 客户端将文件数据发送给服务器
2.** 服务器保存上传的文件数据到服务器端
3.** 服务器响应给客户端一个文件访问地址**
>** 测试地址:http://101.132.72.36:5100/api/upload
>** 键的名称(表单域名称):imagefile
请求方法:POST
请求的表单格式:multipart/form-data 这个格式上传需要格式 ,格式如下+
请求体中必须包含一个键值对,键的名称是服务器要求的名称,值是文件数据
>** HTML5中,JS仍然无法随意的获取文件数据,但是可以获取到input元素中,被用户选中的文件数据
>** 可以利用HTML5提供的FormData构造函数来创建请求体
**
<body><img src="" alt="" id="imgAvatar"><input type="file" id="avatar"><button>上传</button><script>async function upload() {const inp = document.getElementById("avatar");if (inp.files.length === 0) {alert("请选择要上传的文件");return;}const formData = new FormData(); //构建请求体formData.append("imagefile", inp.files[0]);const url = "http://101.132.72.36:5100/api/upload"const resp = await fetch(url, {method: "POST",body: formData //自动修改请求头});const result = await resp.json();return result;}document.querySelector("button").onclick = async function() {const result = await upload();const img = document.getElementById("imgAvatar")img.src = result.path;}</script></body>
使用原生的XMLHttpRequest实现图片上传
<body><input type="file" name="" id="file"><button id="btn" type="submit">上传</button><img src="" id="img" alt=""><script>const url = "http://101.132.72.36:5100/api/upload";const inp = document.getElementById('file');const btn = document.getElementById('btn');const img = document.getElementById('img')btn.onclick = function (e) {if (inp.files.length === 0) {alert('错误')}const fromDate = new FormData()let fil = inp.files[0]console.log(fil)fromDate.append('imagefile', inp.files[0])const xhr = new XMLHttpRequest()xhr.open('POST', url);xhr.send(fromDate)xhr.onreadystatechange = function () {console.log(xhr.readyState)console.log(xhr.status)console.log(xhr.responseText)console.log(xhr.responseText.split('')[0])if (xhr.readyState == 4 && xhr.status == 200) {let data = JSON.parse(xhr.responseText);img.src = data.path;}}}</script></body>
