https://blog.csdn.net/java_qq_99811494/article/details/79681742
html:
-
<form id="form">
-
<input type="file" name="image">
-
</form>
这里依然需要form标签包裹,虽然并不用它来提交。如果非要去掉form,就只能用原生的XMLHttpRequest来实现,但是这家伙是同步的。
jquery:
-
$( document).on("change","#form input",function (e) {
-
upload({
-
url:'vtuce.cn/upload',
-
formNode:this.parentNode,
-
token:'hellothisismytokenstring',
-
sCallback:function (res) {
-
console.log(res);
-
}
-
})
-
});
-
function upload(params) {
-
var data = new FormData(params.formNode);
-
$.ajax({
-
url:params.url,
-
type:'POST',
-
headers:{token:params.token},
-
data:data,
-
dataType:'JSON', //定义返回结果的类型
-
cache: false,
-
contentType:false,
-
processData:false,
-
success:function (res) {
-
params.sCallback && params.sCallback(res);
-
}
-
});
-
}
thinkphp5:
-
public function upload(){
-
$token = Request:: instance()->header( 'token');
-
//$token权限校验。。。
-
$file = Request:: instance()->file( 'image');
-
$type = explode( '/',$file->getInfo('type'));
-
if($type[0] != 'image'){//文件类型过滤
-
return 'error';
-
}
-
if($file->getInfo('size')>102400){//图片大小过滤
-
return 'error';
-
} else{
-
$ext = $type[ 1];
-
$filename = 'somename.'.$ext;
-
move_uploaded_file($file->getInfo( 'tmp_name'),$filename);
-
return 'ok';
-
}
-
}
-
