通用的js异步ajax文件上传函数

无需表单,直接加点击事件即可,

caseimg为input表单,image为图片显示

function upimage() {
$('#form-upload').remove();

$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" value="" /></form>');

$('#form-upload input[name=\'file\']').trigger('click');

if (typeof timer != 'undefined') {
clearInterval(timer);
}

timer = setInterval(function() {
if ($('#form-upload input[name=\'file\']').val() != '') {
clearInterval(timer);

$.ajax({
url: '/manager/atlas_upload',
type: 'post',
dataType: 'json',
data: new FormData($('#form-upload')[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
},
complete: function() {
},
success: function(json) {

if (json['rc']['error']) {
alert(json['rc']['error']);
}
if (json['rc']['success']) {

$('#image').attr('src',json['rc']['src']);
$('#caseimg').val(json['rc']['src']);

}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
}, 500);
}

猜你喜欢

转载自www.cnblogs.com/mengzhilva/p/10658240.html