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); })