直接调用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" accept=".jpg,.jpeg,.gif,.png" style="display:none" onchange ="UploadImg(null,\'' + id + '\')">') document.getElementById(id).click(); } else { let uploadImgElement = document.getElementById(id); let fileObj = uploadImgElement.files[0]; let form = new FormData(); form.append("file", fileObj); xhr = new XMLHttpRequest(); // XMLHttpRequest 对象 xhr.open("post", "//file.qchtc.com/img/upload", true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。 xhr.onload = function (evt) { try { var result = JSON.parse(evt.target.responseText); callback = _callbacks.get(id); callback(result); } catch (e) { console.log(e); } finally { document.getElementById(id).remove(); } }; xhr.onerror = function () { _callbacks.delete(id); document.getElementById(id).remove(); }; xhr.upload.onprogress = function () { //【上传进度调用方法实现】 }; xhr.upload.onloadstart = function () { console.log("正在上传") }; xhr.send(form); //开始上传,发送form数据 } }
调用:
UploadImg((r) => { console.log(r); })