核心提示:ajax代码实现上传图片function submitUpload () {var file = document.querySelector(#image-upload-area).files[0]...
ajax代码实现上传图片
function submitUpload () {
var file = document.querySelector('#image-upload-area').files[0];
if (file) {
var form = new FormData();
var xhr = new XMLHttpRequest();
form.append('save', true);
form.append('file', file);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
var response = xhr.responseText();
try {
if (typeof response === 'string') {
response = JSON.parse(response);
}
} catch (e) {
if (typeof response === 'string') {
showImageUploadError('上传失败');
} else if (response.isSuccess) {
console.log(imageUploadKes);
var tpl = '<img src="%s" />';
ed.insertContent(tpl.replace('%s', response.path));
ed.focus();
removeForeground();
removeBackground();
}
}
}
else if (xhr.status >= 400 && xhr.status < 500) {
showImageUploadError('仔细查看参数是否合法,出错状态吗', xhr.status);
}
else if(xhr.status >= 500) {
showImageUploadError('服务端出错,出错状态码', xhr.status);
}
}
}
xhr.open('POST', imageUploadUrl, true);
console.log(form);
xhr.send(form);
}
}


