直接调用js方法上传图片

var _callbacks = new Map();
function UploadImg(callback, id = null) {
    if (IsNOE(id)) {
      
        id = "_upload_img_" + randomString(8);
        _callbacks.set(id,callback);
        document.body.insertAdjacentHTML("beforeEnd", '<input type="file" id="' + id + '" name="file" style="display:none" onchange ="UploadImg(null,\'' + id + '\')">')
        document.getElementById(id).click();
    } else {
        var uploadImgElement = document.getElementById(id);
        var fileObj = uploadImgElement.files[0];
        var form = document.createElement("form");
        var formData = new FormData(form);
        formData.append("file", fileObj);
        let result=  $.ajax({
            type: "Post",
            url: "//****/img/upload",
            data: formData,
            cache: false,
            async: false,
            contentType: false,
            processData: false,
        }).responseText;
        callback = _callbacks.get(id);
        _callbacks.delete(id);
        document.getElementById(id).remove();
        callback(result);
    }
}

  

调用:

 UploadImg((r) => {
      console.log(r);
 })

  

上一篇:linux – 什么是同时具有实时循环和非实时功能的更好方法


下一篇:自定义事件