php上傳文件,form表單一定要加屬性enctype="multipart/form-data"
html代碼:
<div class="file-box">
<input type="text" name="textfield" id="textfield" class="textbox">
<input type="button" class="button" value="選擇圖片">
<input type="file" name="pic" class="file" id="fileField" onchange="getPicName()">
</div>
css代碼:
.file-box {
position: relative;
width: 340px;
display:inline-block;
}
.file {
position: absolute;
top: 0;
right: 30px;
height: 28px;
filter: alpha(opacity : 0);
opacity: 0;
width: 75px
}
js代碼:(‘斜槓\’需要轉義,在js裏是“\\”,在php裏是“\\\”)
function getPicName( ){
var path=$("#fileField").val();
// alert(path);
// var ex;
// ex=path.split('.');
// alert(ex[ex.length-1]); //jpg 結果
var name;
name=path.split('\\');
var bb=name[name.length-1];
// alert(bb); //AddFile.jpg 結果
// alert(bb.substr(0,bb.indexOf('.'))); //AddFile 結果
$("#textfield").val(bb);
}
php代碼:
$newfile = "default.png";
if(!empty($_FILES["pic"]["tmp_name"])){
echo $_FILES["pic"]["tmp_name"];
echo $_FILES["pic"]["name"];
$ex = substr($_FILES["pic"]["name"],strrpos($_FILES["pic"]["name"],"."));
$newfile = time().$ex;
//file_put_contents("./pic/oout.txt", "xxx");
move_uploaded_file($_FILES["pic"]["tmp_name"],"../wp-content/themes/twentythirteen/pic/".$newfile);
}
最後一點,因爲我的php執行腳本和html是寫在同一個頁面裏的,本頁提交,提交完還是這個頁面,所以提交時,就會刷新頁面,現在要實現判斷哪個表單爲空就不提交,但是submit按鈕已經按下去了,不知道怎麼實現。。想了好久,看到,form表單有個屬性 onsubmit="return false;" 所以只要在js控制這個屬性就ok了。。
if(title!=""&&time!=""){
$('#form1').removeAttr('onsubmit');
}