文件上传

文件上传

流程:

  1. 客户端将文件数据发送给服务器
  2. 服务器保存上传的文件数据到服务器端
  3. 服务器响应给客户端一个文件访问地址

测试地址:http://xxx/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>
    const fileServeUrl = 'http://xxx/api/upload';
    const upload = async ()=> {
        const ipt = document.querySelector('#avatar');
        if (ipt.files.length === 0) {
            alert('请选择文件后在上传!');
            return;
        }
        if(!ipt.multiple) { // 不是多图
            const formData = new FormData(); // 构建请求体
            formData.append('imagefile', ipt.files[0]);
            console.log("form", formData);
            const resp = await fetch(fileServeUrl, {
                method: "POST",
                body: formData
            });
            return await resp.json();
        }
    }
    document.querySelector('button').onclick = async ()=> {
        const resp = await upload();
       document.querySelector('img').src = resp.path;
    }
  </script>
</body>
posted @ 2023-12-16 23:29  HuangBingQuan  阅读(13)  评论(0编辑  收藏  举报