项目还有一周的时间截至 但是交互的速度不是很快 有个发布的是需要图片提交的 ajax只能发送整个form表单 用file属性的input进行按键去提交
html代码如下
<div class="maingoodspage">
<div class="maingoodspage">
展示图片
div>
<div class="showmainImg">
<form action="" method="post" id="sendphotobox">
<input class="coverImageUrl" type="file" id="coverImage" value="" accept="image/gif,image/jpeg,image/jpg,image/png,image/webp" style="opacity: 0;z-index: 20;">
<div id="putMainimg">
<div class="addphoto">
<i class='iconfont' style="color:white;font-size: 40px;">
i>
div>
<div class="tipword">
<span style="color: white;">
添加商品图片
span>
div>
div>
form>
div>
div>
css代码如下
.maingoodspage{
margin-top: 40px;
display: flex;
justify-content:space-around;
margin-left: 22px;
}
.showmainImg{
background-color:#eeeeee ;
width: 200px;
height: 200px;
overflow: hidden;
}
.addphoto{
position: absolute;
/* margin: 0 auto; */
top: 70px;
left: 81px;
}
#sendphotobox{
position: relative;
width: 100%;
height: 100%;
z-index: 10;
}
#coverImage{
width: 100%;
height: 100%;
opacity:0;
z-index: 20;
position: absolute;
top: 0;
left: 0;
}
.addphoto{
z-index: 1;
}
.tipword{
position: absolute;
z-index: 1;
top: 131px;
left: 58px;
}
js代码如下
let coverImage = document.getElementById("coverImage");
let putMainimg=document.getElementById("putMainimg");
coverImage.addEventListener('change',function (){
// 通过files属性拿到对象
const{files}=this;
console.log(files);
const mainPhotof=files[0];
//取出files第一个对象
//是个类数组对象 代表一组选中的对象
const img=document.createElement("img");
img.src=URL.createObjectURL(mainPhotof);
//URL.createObjectURL()用来上传 下载的文件 流媒体生成一个url文件
//代表了file对象的url
//创建img将src设置成这个url
img.style.width='200px';
img.style.height='200px';
putMainimg.innerHTML=img;
console.log(img);
senduserphoto();
})
function senduserphoto(){
let mainFormate=new FormData();
console.log(mainFormate);
console.log(coverImage.files[0]);
// file的内容
mainFormate.append('file',coverImage.files[0]);
$.ajax({
type: "POST",
url: url,
contentType:false,//请求服务器的时候数据有非字符串的形式
processData:false,//fordata对象不需要转化为参数字符串
data: mainFormate,//传入实例化表单对象
//表单传进去
cache:false,
success: function (result) {
console.log(result)
},
error: function (err) {
console.log(err)
}
})
}
总结
马上要考核了 得赶赶