HTML代码
<div class="box-body"><div class="form-group" id="test"><label for="background_img">上传海报背景图</label><input type="file" id="background_img"><img id="background" src="" width="67.5" height="120" alt=""><input type="text" class="form-control id="background_input" readonly value=""></div>
</div>
javascript代码
<script type="text/javascript">var background_img=document.querySelector("#background_img");$("#background_img").on("change",function() {var file=this.value;var all_img_ext=".jpg|.jpeg|.gif|.bmp|.png|";var ext = file.substring(file.lastIndexOf(".")).toLowerCase();//路径中所有字母全部转为小写if(all_img_ext.indexOf(ext+"|")==-1){swal("请上传 "+all_img_ext+" 类型的文件,当前文件类型为"+ext);return false;}//获取文件对象,files是文件选取控件的属性,存储的是文件选取控件选取的文件对象,类型是一个数组var fileObj = background_img.files[0];//创建formdata对象,formData用来存储表单的数据,表单数据时以键值对形式存储的。var formData = new FormData();formData.append('background_img', fileObj);$.ajax({url: "{:url('admin/agent/uploads')}",type: "post",dataType: "json",data: formData,// async: false,// cache: false,contentType: false,processData: false,beforeSend:function () {/**这里用的sweetalert插件,可自定义遮罩层来提示用户**/swal('正在上传');$('body .sa-confirm-button-container .confirm').hide();},success: function (json_data) {if(json_data.code==1){$("#background").attr('src',json_data.data)$("#background_input").val(json_data.data)swal("上传成功");}},error:function(XMLHttpRequest,textStatus,errorThrown){swal('error...状态文本值:'+textStatus+" 异常信息:"+errorThrown)//pop(2,'error...状态文本值:'+textStatus+" 异常信息:"+errorThrown,true)}});});</script>
PHP代码上传至阿里云OSS(只是做demo演示,服务端没有做文件类型大小等判断,请开发者自行添加)
public function uploads()
{$uploadpath = "agent/poster/resource/test/";if(isset($_FILES['background_img'])){$file=$_FILES['background_img'];$oss_filename='background_img';}if($file['error'] == 0){// 服务器路径$localpath = $file['tmp_name'];$filename = $file['name'];$filename = $oss_filename .'.'. getExt($filename);// OSS路径$uploadpath .= $filename;$url= uploadOss($localpath, $uploadpath);return get_response($url,1,'上传成功');}
}
/*全局返回函数*/
function get_response($data,$code,$message){return json(['data'=>$data,'code'=>$code,'message'=>$message]);
}
/*** 上传阿里云* @param $localpath 本地路径* @param $uploadpath 上传路径* @return mixed*/
function uploadOss($localpath, $uploadpath){import('.OSS.autoload', '', '.php');$accessKeyId = Config::get('OSS')['ACCESS_KEY_ID'];//去阿里云后台获取秘钥$accessKeySecret = Config::get('OSS')['ACCESS_KEY_SECRET'];//去阿里云后台获取秘钥$endpoint = Config::get('OSS')['ENDPOINT'];//你的阿里云OSS地址$ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);$bucket = Config::get('OSS')['BUCKET'];//oss中的文件上传空间$oss = $ossClient->uploadFile($bucket, $uploadpath, $localpath, $options = NULL);if($oss['info']['http_code'] == 200){return $oss['info']['url'];} else {return $oss['info']['http_code'];}}