使用ajax实现文件上传,使用input实现本地图片展示
一、实现本地图片预览
HTML:
<input type="file" id="chooseImage" name="myfile" value="" class="layui-btn">
<img style="width: 150px;height: 150px;display: none" id="cropedBigImg" value='custom' alt="lorem ipsum dolor sit" data-address='' title="自定义背景"/>
JS:(使用JQuery)
$(function (){
$('#chooseImage').on('change',function(){
if ($(this)[0].files[0]==null){
$('#cropedBigImg').css("display","none");
}else {
var filePath = $(this).val(),
fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
src = window.URL.createObjectURL(this.files[0]);
if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {
$('#cropedBigImg').css("display","none");
error_prompt_alert('上传错误,文件格式必须为:png/jpg/jpeg');
return;
}
$('#cropedBigImg').attr('src',src).css("display","inline-block");
}
});
})
样式展示:
二、AJAX上传文件
关键代码:
var formData = new FormData();
formData.append("myfile", $("#chooseImage")[0].files[0]);
$.ajax({
type: "post",
url: "/index/reviseAdminInfo",
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(data){
}
)}
全部代码:
var formData = new FormData();
if($("#chooseImage")[0].files[0]!=null){
formData.append("myfile", $("#chooseImage")[0].files[0]);
}
formData.append("adminUserName",data.field.adminUserName);
formData.append("adminPassword",data.field.adminPassword);
formData.append("adminId",data.field.adminId);
$.ajax({
type: "post",
url: "/index/reviseAdminInfo",
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(data){
console.log(data==="1")
if (data==="1"){
layer.msg("修改成功",{
icon: 1,
time: 1500
},function (){
miniTab.deleteCurrentByIframe();
})
}else {
layer.msg("修改失败",{
icon: 2,
time: 2000
})
}
},
error: function (){
layer.msg("修改失败",{
icon: 2,
time: 2000
})
}
});
time: 2000
})
}
});