前台页面:
$(
"#feature").
on(
"change",
function(){
// console.log(this.files);
var file =
this.
files[
0];
var data =
new
FormData();
data.
append(
"file",file);
$.
ajax({
type:
"post",
url:
"api/posts-addUpload.php",
data: data,
contentType:
false,
processData:
false,
success:
function (
res) {
if (
res.
code==
1) {
$(
".help-block").
attr(
"src",
res.
src).
show();
}
}
});
});
后台php页面:
<?php
$file =
$_FILES[
"file"];
// print_r($file);
// Array
// (
// [name] => icon-40.png
// [type] => image/png
// [tmp_name] => C:\Windows\phpE853.tmp
// [error] => 0
// [size] => 6442
// )
$ext=
strrchr(
$file[
'name'],
'.');
$fileName =
time().
rand(
10000,
99999).
$ext;
$bool =
move_uploaded_file(
$file[
'tmp_name'],
'../../static/uploads/'.
$fileName);
$response = [
"code"=>
0,
"msg"=>
"操作失败"];
if (
$bool) {
$response[
"code"]=
1;
$response[
"msg"]=
"操作成功";
$response[
"src"]=
"../static/uploads/".
$fileName;
}
header(
"content-type:application/json");
echo
json_encode(
$response);
?
>