客服系统vue源码聊天界面,ajax上传图片功能实现,动态异步上传文件

在线客服系统的聊天界面上,有上传图片按钮功能,使用js实现ajax上传图片功能

html部分,有一个点击事件

 <div class="iconExtendBtn" @click="uploadImg">
                        <div class="elIcon el-icon-picture"></div>
                        <div>图片</div>
                    </div>

js部分,动态创建input进行上传文件

//上传图片
            uploadImg:function (){
                let _this=this;
                let input = document.createElement("input");
                input.type = "file";
                input.accept = "image/gif,image/jpeg,image/jpg,image/png";
                input.style.display = "none";
                input.addEventListener("change", function(e) {
                let formData = new FormData();
                let file = e.target.files[0];
                formData.append("imgfile", file); //传给后台的file的key值是可以自己定义的
                fetch(_this.ApiHost+'/uploadimg', {
                  method: "POST",
                  body: formData
                })
                .then(response => response.json())
                .then(res => {
                  console.log(res);
                   
                })
                .catch(error => {
                  console.error(error);
                });
                });
                document.body.appendChild(input);
                input.click();
            },

后端通过imgfile文本域接收数据