html

1
2
3
4
5
<form id="uploadForm" enctype="multipart/form-data">
上传文件:<input type="file" id="uploadFile" />
</form>
<div id="div">
</div>

js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$("#uploadFile").on("change",function(){
var formData = new FormData($( "#uploadForm" )[0]);
formData.append("image", $(this).get(0).files[0]);
$.ajax({
url: '{:url("Test/uploadImg")}' ,
type: 'POST',
data: formData,
cache: false, //
contentType: false, // 不要设置Content-Type请求头
processData: false, // 不要处理发送的数据
success: function (data) {
console.log("路径:",data)
$("#div").html("").html('<img src="'+data+'" width="640" height="320" />');
},
error: function (e) {
console.log(e)
}
});
})

php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//例子
public function uploadImg()
{
$file = request()->file('image');
$path = Env::get('root_path').'/public/upload/test';
$info = $file->move($path);
if($info){
$fileName = $info->getSaveName();
$src = "/upload/test/".$fileName;
}else{
// 上传失败获取错误信息
$src = $file->getError();
}
return json($src);
}