PHP 上傳檔案
阿新 • • 發佈:2019-02-06
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裡是“\\\”)
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); }
$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');
}