异步上传是一个很蛋疼的问题,今天就来说说异步上传的故事
第一步 引入ajaxSubmit这个js插件
<!--异步提交图片-->
<script src="__PUBLIC__/js/jquery.ajaxSubmit.js"></script>
这时候开始页面处理
<input type="file" id="file" name="b_head" class="col-xs-6 ttee" onchange="changePhoto();" style="display: none" />
<label for="file">
<img <if condition="$data.user_b_head neq ''">src="upload/{$data.user_b_head}"<else/>src="__PUBLIC__/image/ic_upload.png"</if> id="new_pic" alt="" class="col-xs-6 img-responsive"/>
</label>
<input type="hidden" name="user_b_head" id="head"/>
讲file文件关联到img标签里面,点击img图片就能触发file进行选择文件
开始js处理
<script>
$(".ttee").click(function () {
$(this).wrap("<form id='addPic' method='post' action="+"{:U('upload')}"+" enctype='multipart/form-data'></form>");
});
function changePhoto() {
$('#addPic').ajaxSubmit({
dataType:'json',
success:function(data){
$('.ttee').unwrap();
$('#new_pic').attr('src',"upload/"+data.src);
$("#head").val(data.id);
},
error:function(err){
$('.ttee').unwrap();
console.log(JSON.stringify(err));
}
})
}
</script>
这里不难看的出来 在点击的时候给父级包裹一层form表单
当图片选择完时候触发时间 进行插件的提交
$('.ttee').unwrap();
这个则是进行移除form表单
后台接收和平常是一样一样的
我这里是用tp写的
//上传图片
public function upload(){
$file = $this->setUpload($_FILES['b_head']);
$src = $file['savepath'].$file['savename'];
$data['src'] = $src;
//进行数据插入
$id = M('picture')->add(array('path'=>$src));
$data['id'] = $id;
echo json_encode($data);
}
//上传图片
private function setUpload($file){
header("Content-Type: text/html;charset=utf-8");
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 3145728 ;// 设置附件上传大小
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
$upload->rootPath = './upload/'; // 设置附件上传根目录
$upload->savePath = date("Y",time())."/".date("m",time())."/".date("d",time())."/"; // 设置附件上传(子)目录
// 上传文件
$info = $upload->uploadOne($file);
if(!$info) {// 上传错误提示错误信息
$this->success($upload->getError());exit;
}else{// 上传成功
return $info;
}
}
这样 异步上传图片就完事了,欢迎评论,私人博客还在建设当中
www.poison2016.cn