上傳圖片功能的實現
阿新 • • 發佈:2018-12-17
html 中
< form method="POST" action="..." enctype="multipart/form-data"> < div class="box" style="padding:20px 25px;"> // 隱藏域傳 tid < input type="hidden" name="data[tid]" value="<{$tid}>"> < p>標題:< /p> < input type="text" name="data[title]" class="ma_title" placeholder="請輸入標題"> < p>上傳圖片:< /p> < div class="ma_photo"> < input id="biaoqian_file" name="img" type="file" style="width:80px;height:80px;position: absolute;top: 10px;opacity: 0;"> < img src="/tpl/default/static/images/hm.png" alt="" style="height:80px;margin-top: 10px;border-radius: 5px;vertical-align: top;"> < div class="ma_photo_box"> 這個div是用來顯示圖片的 < /div> < /div> < p>記錄回憶:< /p> < textarea name="data[content]" class="ma_neirong" placeholder="請填寫您要記錄的故事">< /textarea> < /div> < button class="next">下一步< /button>
< /form>
js 中
// 上傳圖片並展示,可回顯可傳值給後臺
document.getElementById('biaoqian_file').onchange = function() { var imgFile = this.files[0]; var fr = new FileReader(); fr.onload = function() { // alert(fr.result); $('.ma_photo_box').append('<img src="'+fr.result+'" alt="">'); $('.ma_photo_box').width($('.ma_photo_box img').length * 90); // document.getElementById('image').getElementsByTagName('img')[0].src = fr.result; }; fr.readAsDataURL(imgFile); };
控制器中
獲取前臺傳過來的圖片並上傳到一個位置
$file = $_FILES['img']; //得到傳輸的資料,前臺標籤名是 img,所以用 img 來接收 echo '<pre>'; var_dump($file); var_dump($file['tmp_name']); //得到檔名稱 $name = $file['name']; $type = strtolower(substr($name,strrpos($name,'.')+1)); //得到檔案型別,並且都轉化成小寫 $allow_type = array('jpg','jpeg','gif','png'); //定義允許上傳的型別 //判斷檔案型別是否被允許上傳 if(!in_array($type, $allow_type)){ //如果不被允許,則直接停止程式執行 return ; } //判斷是否是通過HTTP POST上傳的 if(!is_uploaded_file($file['tmp_name'])){ //如果不是通過HTTP POST上傳的 return ; } $upload_path = "D:/phpstudy/WWW/.../static/uploadimages/"; //上傳檔案的存放路徑 //開始移動檔案到相應的資料夾 if(move_uploaded_file($file['tmp_name'],$upload_path.$file['name'])){ echo "Successfully!"; }else{ echo "Failed!"; }