注意form表单要填写enctype="multipart/form-data"
前台html:
<div class=" clearfix cl">
<label class="form-label col-2">图片:</label>
<div class="role" onclick="file(this)">
<img src="" alt="" id="goods_1" class="file" >
<span style="color: #ccc;">上传图像</span>
<input type="file" name="goods_imgs[]" class="file" value="" id="goods1" onchange="le(this)">
</div>
<div class="role" style="display: none" onclick="file(this)">
<img src="" alt="" id="goods_2" class="file" >
<span style="color: #ccc;">上传图像</span>
<input type="file" name="goods_imgs[]" class="file" value="" id="goods2" onchange="le(this)">
</div>
<div class="role" onclick="copy(this)">
<span style="color: #ccc;">+</span>
</div>
<!-- <input type="file" name="img" class="file" value="" > -->
</div>
js:
<script type="text/javascript">
//点击圆框时上传图片
function file(evn) {
var img_obj = $(evn).children(".file")
var file_id = $(img_obj[1]).attr("id")
document.getElementById(file_id).click()
}
//点击时复制角色框
function copy(evn) {
var obj = $(evn).prev();
var num = $(".role").length
console.log(num)
$(obj).clone().insertBefore(evn);
$(obj).css("display","block")
var img_obj = $(obj).children(".file")
console.log(img_obj)
var img_id = $(img_obj[0]).attr("id","goods_"+num)
var file_id = $(img_obj[1]).attr("id","goods"+num)
}
//左侧图像点击时显示图像
function le(evn){
var id = $(evn).attr('id');//获取id
var num = "goods_"+id.substr(5,1);
var file = event.target.files[0];
if (window.FileReader) {
var reader = new FileReader();
reader.readAsDataURL(file);
//监听文件读取结束后事件
reader.onloadend = function (e) {
var divObj= $(evn).prev() //获取div的DOM对象
$(divObj).html("") //插入文件名
$("#"+num).css("display","block");
$("#"+num).attr("src",e.target.result); //e.target.result就是最后的路径地址
};
}
}
</script>
后台接收数据:
public function upload_images(Request $request)//上传图片,多图上传
{
$char=$this->random_string(16);
$file = $_FILES["file"];
if ($file==null) {
exit(json_encode(array('code'=>1, 'msg'=>'未上传图片')));
}
// 获取文件后缀
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
// 判断文件是否合法
if(!in_array($extension, array("gif","jpeg","jpg","png"))){
exit(json_encode(array('code'=>1, 'msg'=>'上传图片不合法')));
}
//创建文件夹获取当前年月日
$folder="/mstyle/upload/images/".date('Y-m-d');
if(!is_dir('.'.$folder)){
mkdir('.'.$folder,0777);//创建年+月的文件夹权限为最高
}
// $info = move_uploaded_file($file['tmp_name'], '.'.$folder.'/'.$file['name']); //移动文件到指定目录 建议文件名自己在修改一下
$info = move_uploaded_file($file['tmp_name'], '.'.$folder.'/'.$char.'.'.$extension); //移动文件到指定目录 建议文件名自己在修改一下
// dd($extension);
$img = $folder.'/'.$char.'.'.$extension;
// exit(json_encode(array('code'=>0, 'msg'=>$img)));
$res=['imgurl'=>$img];
$ArrDate = ['code' => 0, 'data' => $res, 'token' => $request->input('token')];
return BaseFun::jsonReturn($ArrDate);
}
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
评论 (0)