文件上传

108 阅读1分钟

一 单文件上传

console.log(window.URL.createObjectURL(fileEl.files[0]));
updateImg.src = window.URL.createObjectURL(fileEl.files[0]);
 
<input type="file" id="myfile" accept="image/png, image/jpeg">
    <button id="upload">上传</button>
    <script>
        upload.onclick = function () {
            // myfile.files[0] 获取选择的文件的信息
            console.log(myfile.value, myfile.files[0]);
            // 文件传输必须使用formData格式
            // new FormData(form) 代表将form表单里面的带有name属性的表单元素都提取出来以key/vaule的形式放入
            var data = new FormData();  // 创建出来一个空的formData对象
            data.append('file', myfile.files[0]);
            var xhr = new XMLHttpRequest();
            xhr.open('post', 'http://192.168.204.63:3005/api/add');
            xhr.send(data);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    console.log(xhr.responseText);
                }
            }
        }
    </script>

QQ图片20230707193256.png

var url =``;
         avatar.onclick=function()
             file.click();
         }
         file.onchange=function(){
             var data=new FormData();
             data.append('avatar', file.files[0]);
             fetch('http://127.0.0.1:3000/api/avatar',{
                 method:"post",
                 body:data
             }).then(res=>res.json()).then(res=>{
                 if (!res.code) {
                     alert(res.msg)
                     return
                 }
                 avatar.src=`http://127.0.0.1:3000/avatar/`+res.avatar;
                 url=res.avatar;
             })
         }

二 多文件上传

<input type="file" id="myfile" webkitdirectory>
    <button id="upload">上传</button>
    <script>
        upload.onclick = function () {
            // myfile.files[0] 获取选择的文件的信息
            console.log(myfile.value, myfile.files);
            var data = new FormData();
            for (let i = 0; i < myfile.files.length; i++) {
                data.append('file', myfile.files[i]);
            }
            var xhr = new XMLHttpRequest();
            xhr.open('post', 'http://192.168.204.63:3011/api/add');
            xhr.send(data);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    console.log(xhr.responseText);
                }
            }
        }
    </script>