PHP 微信端上传图片,上传logo和banner图,哪位大神传授一下经验啊,有demo更好,可以加分
1个回答
展开全部
<div class="header" >
<span>头像</span>
<div class="head_r" style="position: relative">
<img class="portrait_line" id="show_portrait" src="{$agent['portrait']}">
<img src="__IMAGES__/more.png">
<input type="file" name="portrait" id="portrait" data-server="{:U('Home/Upload/mobile_upload_portrait')}" style="width: 100%;height: 100%;position: absolute;left: 0px;top: 0px;opacity: 0;">
</div>
</div>
最后一个input file弄成透明的,占据整个你要触发上传的位置。
重点在下面,用原生ajax上传提交图片,并把上传后服务器本地的地址传回来,通过js付到表单里,并把图片缩小预览贴出来。
<script>
$(function(){
$("input#portrait").on("change",function(){
changepic('portrait','show_portrait');
});
});
var xhr;
var returnimg="";
var returninput="";
function changepic(id,img,input){
returnimg=img;
returninput=input;
var fileObj = document.getElementById(id).files[0];
var uploadServer = $("#"+id).attr("data-server");
var form = new FormData();
form.append("portrait", fileObj);
createXMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("post", uploadServer, true);
xhr.send(form);
}
function createXMLHttpRequest()
{
if(window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
}
function handleStateChange()
{
var $loading=layer.open({type:2,})
if(xhr.readyState == 4)
{
if (xhr.status == 200 || xhr.status == 0)
{
var result = xhr.responseText;
var json = eval("(" + result + ")");
if(json.result=='success'){
$.ajax({
type:'post',
url:'/index.php/Wap/Self/updatePortrait',
data:{
portrait:json.url,
},
success:function(){
},
error:function(){
alert('服务器错误');
},
});
$("#"+returnimg).attr("src",json.url);
layer.close($loading);
}
else{
alert('上传头像失败'+json.msg);
layer.close($loading);
}
}
}
}
</script>
然后是ajax上传的接口
public function mobile_upload_portrait(){//手机端上传头像
if(IS_POST){
$upload=new Upload();
$upload->maxSize = 3*1024*1024;//3M
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');
$upload->rootPath = './';
$upload->savePath = '/Uploads/';
$upload->autoSub = true;
$upload->subName = array('date','Ymd');
$upload->saveName = 'uniqid';
if(!is_dir($upload->savePath)){
mkdir($upload->savePath);
}
$info = $upload->uploadOne($_FILES['portrait']);
if(!$info) {
$result=array('result'=>'fail','msg'=>'请上传3M以下的图片');
}else{
$result=array('result'=>'success','url'=>$info['savepath'].$info['savename']);
}
$this->ajaxReturn($result);
}
}
代码是Thinkphp的项目截出来的,页面上有模板的痕迹,最后一段php的接口,也用了tp自带的文件上传类。不过看得懂的话,这些都不影响理解。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询