html:
<form enctype="multipart/form-data" method="post">
<input type="file" id="uploadFile" runat="server" />
<input type="button" id="btnUpload" value="確定" onclick="uploadImage()" />
<div id="imgDiv">
</div>
</form>
<script type="text/javascript">
function uploadImage() {
//判斷是否有選擇上傳文件
var imgPath = $("#uploadFile").val();
if (imgPath == "") {
alert("請選擇上傳圖片!");
return;
}
//判斷上傳文件的后綴名
var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp') {
alert("請選擇圖片文件");
return;
};
var formdata = new FormData();
var fileObj = $("#uploadFile").get(0).files;
formdata.append("file", fileObj[0]);
formdata.append("aid", 30);
formdata.append("nickname", "你好");
$.ajax({
type: "POST",
url: 'test.php',
data: formdata,
processData: false,
contentType: false,
cache: false,
success: function(data) {
//alert("上傳成功");
$("#imgDiv").empty();
$("#imgDiv").html(data);
$("#imgDiv").show();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//alert("上傳失敗,請檢查網絡后重試");
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
test.php:
<?php
//如果接收的數據包含圖片文件
if(isset($_FILES['file'])){
$aid = intval($_POST['aid']);
$nickname = ($_POST['nickname']);
//獲取圖片的臨時路徑
$image = $_FILES["file"]['tmp_name'];
//只讀方式打開圖片文件
$fp = fopen($image, "r");
//讀取文件(可安全用於二進制文件)
$file = fread($fp, $_FILES["file"]["size"]); //二進制數據流
//保存地址
$imgDir = 'account_imgs/';
//要生成的圖片名字
//$filename = date("Ym")."/".md5(time().mt_rand(10, 99)).".jpg"; //新圖片名稱
$filename = "2017new.jpg";
//新圖片的路徑
$newFilePath = $imgDir.$filename;
$data = $file;
$newFile = fopen($newFilePath,"w"); //打開文件准備寫入
fwrite($newFile,$data); //寫入二進制流到文件
fclose($newFile); //關閉文件
//寫入數據庫
$sql = "update account set nickname = '".$nickname."', img = '".$filename."' where aid = ".$aid;
if(!$db->query($sql)) {
Json_out(array('result'=>'imgfail'));
exit;
}else{
Json_out(array('result'=>'imgsuccess'));
exit;
}
} else{
$aid = intval($_REQUEST['aid']);
$nickname = $_REQUEST['nickname'];
$sql = "update `account` set nickname = '".$nickname."' where aid = ".$aid;
if(!$db->query($sql)) {
Json_out(array('result'=>'fail'));
exit;
}else{
Json_out(array('result'=>'noimgsuccess'));
exit;
}
}
?>