其他分享
首页 > 其他分享> > 直接调用js方法上传图片

直接调用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);
 })

  

标签:调用,false,callback,js,callbacks,var,document,上传,id
来源: https://www.cnblogs.com/yesicoo/p/14510751.html