<p><input type="file" id="upfile"></p>
<p><input type="button" id="upJQuery" value="用jQuery上传"></p>
js代码:
<script>
function uploadPic() {
var host = window.location.host;//获取网站主机地址
var formData = new FormData();
formData.append("filename", $("#upfile").get(0).files[0]));
$.ajax({
type:"POST",
url:"/api/upload/upload",
data: formData,
cache: false,
contentType: false, // 使数据不做处理
processData: false, // 不要设置Content-Type请求头
success: function (data) {
if(data.status == 200){
alert('成功');
}else{
alert('失败');
}
}
});
}
</script>
PHP代码:
/**
* 单图片上传
*/
public function upload() {
$file = $this->request->file('filename');
if ($file) {
$info = $file->validate(['ext'=>'jpg,png,gif,jpeg,png'])->move('uploads');
if ($info) {
$getSaveName=str_replace("\\","/",$info->getSaveName());
apiReturn($getSaveName,200 , '上传成功');
} else {
apiReturn('', 0, $file->getError());
}
} else {
apiReturn('', 0, '图片不存在');
}
}