html代码
<input type="file" id="shangchuan" value="" />
<input type="hidden" name="head_pic" id="head_pic" value="<{$userInfo.head_pic}>"/>
<img src="/Public/Uploads/<{$userInfo.head_pic}>" alt="" id="head_pic_img">
js 代码
$("#shangchuan").change(function(){
var formData = new FormData();
formData.append("file",$("#shangchuan")[0].files[0]);
$.ajax({
url:"<{:U('Member/uploadImgs')}>",
type:"post",
data:formData,
dataType:"json",
mimeType:"multipart/form-data",
processData: false, //用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
success:function(result){
if(result.status == 200){
$("#head_pic").val(result.data.head_pic);
$("#head_pic_img").attr("src","/Public/Uploads/"+result.data.head_pic);
layer.msg("上传成功",{time:2000});
}else{
layer.msg(result.msg,{time:2000});
}
}
})
})
php代码
protected function _upload_init($upload)
{
$allow_max = 2048; //读取配置
$allow_exts = explode(',', 'jpg,gif,png,jpeg,swf,bmp'); //读取配置
$allow_max && $upload->maxSize = $allow_max * 1024; //文件大小限制
$allow_exts && $upload->allowExts = $allow_exts; //文件类型限制
$upload->saveRule = 'uniqid';
return $upload;
}
/**
* 上传头像接口
*/
public function uploadImgs()
{
import('Org.Net.UploadFile');
$upload = new \UploadFile(); // 实例化上传类
$upload->maxSize = 9145728; // 设置附件上传大小
//$upload->allowExts = explode(',', 'jpg,gif,png,jpeg,bmp'); // 设置附件上传类型
$upload->saveRule = 'avatar'; //设置上传头像命名规则(临时图片),修改了UploadFile上传类
//完整的头像路径
$path =UPLOAD_PATH.'user/' . date('Ymd') . '/';
if (!file_exists($path)) {
mkdir($path);
}
$thumb_index = array(
'width' => '75',
'height' => '75',
'remove_origin' => true,
'isdate' => false,
);
if ($thumb_index) {
$upload->thumb = true;
$upload->thumbMaxWidth = $_REQUEST['width'] ?$_REQUEST['width']:$thumb_index['width'];
$upload->thumbMaxHeight = $_REQUEST['height'] ?$_REQUEST['height']:$thumb_index['height'];
$upload->thumbPrefix = '';
$upload->thumbExt = isset($thumb_index['ext']) ? $thumb_index['ext'] : '';
if($_REQUEST['file']){
$upload->thumb_mode = $_REQUEST['file'];
}
}
$upload->savePath = $path;
$upload = $this->_upload_init($upload);
if (!$upload->upload()) {
// 上传错误提示错误信息
$this->ajaxReturn(201, $upload->getErrorMsg());
} else {
// 上传成功 获取上传文件信息
$info = $upload->getUploadFileInfo();
$returnPath=array('head_pic'=>'/user/' . date('Ymd') . '/' . $info[0]['savename']) ;
$this->ajaxReturn(200,'上传成功!', $returnPath);
}
}