当前位置: 移动技术网 > IT编程>网页制作>CSS > ajax代码实现上传图片

ajax代码实现上传图片

2018年03月28日  | 移动技术网IT编程  | 我要评论
ajax代码实现上传图片 function submitUpload () { var file = document.queryS

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

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网