html
<div class="createMzR">
<div class="index_middlezik">
<div class="index_middlezic" id="categoryIcons" onclick="upload_img(this);" data="img1">
<div class="index_middlezicc">
<img src="../img/daikuan/upload_img.png" alt="" class="index_middlezi">
</div>
<input type="file" style="display:none;" onchange="file_change(this);" class="upload_imgp">
</div>
</div>
</div>
js
function upload_img(e){
$(e).eq(0).find('.upload_imgp')[0].click();
}
//确定文件
function file_change(e){
// console.log($('#txPath').val());
console.log($(e)[0]);
console.log($(e).val());
add_file(e);
}
//上传文件
function add_file(e) {
if($(e)[0].files[0]){
// 判断文件类型及大小
var formData = new FormData();
formData.append("file", $(e)[0].files[0]);
formData.append("type", 3);
console.log($(e)[0].files[0]);
console.log(formData)
$.ajax({
url: base_url+'/upload/uploadFile',
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'text',
// timeout: 20000, //超时时间设置为20秒;
beforeSend: function(request) {
request.setRequestHeader("Authorization", localStorage.getItem("token"));
},
success: function (res) {
check_token(res);
var res=JSON.parse(res);
console.log(res);
// console.log(res.dataxz);
if(res.code== 200){
var par=$(e).parent();
$(par).attr('data-src',res.data.imgUrl);
var img_html='<img src="'+res.data.imgUrl+'" alt="" class="index_middlezi2">';
$(par).find('.index_middlezicc').html(img_html);
$(e).val('');//清空上传input的值
window.sessionStorage.setItem('categoryIcons',res.data.imgUrl);
}else if(token_alert_pd){
if(res.message){
alert(res.message);
}
}
},
error:function (res){
console.log(res);
// alert('网络连接失败');
}
});
}
}