1. 程式人生 > >通用的js異步ajax文件上傳函數

通用的js異步ajax文件上傳函數

x文件 trigge lse thrown art for data != tin

無需表單,直接加點擊事件即可,

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

通用的js異步ajax文件上傳函數