php js上传

作者: adm 分类: php 发布时间: 2021-08-17 09:47
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.upload {
position: relative;
display: inline-block;
background: #D0EEFF;
border: 1px solid #99D3F5;
border-radius: 4px;
padding: 4px 12px;
overflow: hidden;
color: #1E88C7;
text-decoration: none;
text-indent: 0;
line-height: 40px;
width: 150px;
height: 40px;
text-align: center;

}
#file {

display:none;

}
#avatars{
width:50px;
height:50px;
}
</style>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<img id="avatars" src="">
<input type="hidden" name="icon" id="head" value="">
<input class="upload" type="file" id="file" name="file">
<a onClick="document.querySelector('#file').click()" class="upload">选择文件</a>
<script>
$('#file').on('change', function( e ){
//e.currentTarget.files 是一个数组,如果支持多个文件,则需要遍历

var formData = new FormData();
formData.append('file','file');
formData.append('file',e.currentTarget.files[0]);
$.ajax({
type: "POST",
url: "{:url('index/index/upload')}",//+tab,
data: formData,// 你的formid
dataType: "json",
async: false,
cache: false,
contentType: false,
processData: false,
success: function (result) {
$('#head').val(result.data);
$('#avatars').attr('src', result.path);
}
});
});

</script>
</body>
</html>

php 代码

public function upload(){
$save_url = ROOT_PATH.'public/head/';
if(!is_dir($save_url)){
mkdir($save_url,0755,true);
}
$code =input('file');
//设置目录是否有写的权限
if (!is_writable($save_url)) {
return json(['status' =>-1,'msg' =>'文件上传的目录:'.$save_url.'没有写入权限!!']);
}
$file = request()->file($code);
if($file) {
$image_upload_limit_size = 2000000;
$info = $file->validate(['size' => $image_upload_limit_size, 'ext' => 'jpg,jpeg,gif,png'])->rule(function ($file) {
return md5(mt_rand()); // 使用自定义的文件保存规则
})->move($save_url);
if ($info) {
$file_path = '/head/' . $info->getFilename();
} else {
// 上传失败获取错误信息
return json(['status' =>-1,'msg' =>$file->getError()]);
}
}
if (isset($file_path)) {
return json(['status' => 1,'msg' =>'上传成功','data' =>$file_path,'path' =>request()->root(true).$file_path]);
}
return json(['status' => -1,'msg' =>'上传失败']);
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!