PHP實現多圖片上傳

PHP實現多圖片上傳

今天在工做中遇到了一個需求:一個表單實現多個上傳圖片,相似於QQ空間上傳照片的模式。即:能夠一次性上傳多個圖片,可是封面圖片只有一個。php

最早,最重要的事,在服務器上對文件進行讀寫操做的時候,必定要看權限,若是沒有權限,全是蝦扯蛋,爲何這樣說,由於全是淚。html

首先,前端頁面:index.html前端

<html>
<head><title>多個文件上傳表單</title></head>
<body>
<style>
    form{
        margin: 20px;
        padding: 10px;
    }

    #picInput>input{
        display: block;
        margin: 10px;
    }


</style>
<form action="pic.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000">
    <div id="picInput">
        上傳圖片:<input type="file" name='myfile[]'>
    </div>
    <input id="addBtn" type="button" onclick="addPic1()" value="繼續添加圖片"><br/><br/>
    <input type="submit" value="上傳文件">
</form>

<script>
    function addPic1(){
        var addBtn =  document.getElementById('addBtn');
        var input = document.createElement("input");
        input.type = 'file';
        input.name = 'myfile[]';
        var picInut = document.getElementById('picInput');
        picInut.appendChild(input);
        if(picInut.children.length == 3){
            addBtn.disabled = 'disabled';
        }
    }
</script>
</body>
</html>mysql

 

知識點:sql

1.經過JS動態添加input結點和設置屬性,當大於3個上傳圖片的時候就再也不給予上傳圖片的機會了。數據庫

2.這裏最主要的是input輸入框的name值,經過動態的添加數組元素,將全部上傳的圖片動態添加到數組當中。後端

 

後端處理功能數組

Connection.php服務器

1.讀取和存儲都須要用到鏈接數據庫,因此能夠把它封住一下,養成良好的習慣app

<?php
//建立對象並打開鏈接,最後一個參數是選擇的數據庫名稱
$mysqli = new mysqli('localhost','root','','test');
//檢查鏈接是否成功
if (mysqli_connect_errno()){
    //注意mysqli_connect_error()新特性
    die('Unable to connect!'). mysqli_connect_error();
}

 

pic.php處理功能

<?php
require_once 'connection.php';
$file = $_FILES['myfile'];  //獲得傳輸的數據,以數組的形式
$name = $file['name'];      //獲得文件名稱,以數組的形式
$upload_path = "zhouqi666.cn/test/images/"; //上傳文件的存放路徑
//當前位置

foreach ($name as $k=>$names){
    $type = strtolower(substr($names,strrpos($names,'.')+1));//獲得文件類型,而且都轉化成小寫
    $allow_type = array('jpg','jpeg','gif','png'); //定義容許上傳的類型
    //把非法格式的圖片去除
    if (!in_array($type,$allow_type)){
        unset($name[$k]);
    }
}
$str = '';
foreach ($name as $k=>$item){
    $type = strtolower(substr($item,strrpos($item,'.')+1));//獲得文件類型,而且都轉化成小寫
    if (move_uploaded_file($file['tmp_name'][$k],$upload_path.time().$name[$k])){
        //$str .= ','.$upload_path.time().$name[$k];
        echo 'success';
    }else{
        echo 'failed';
    }
}

//向指定id插入圖片地址(雖然是插入,可是是更新字段,不要迷糊了)
$uid = 1;
$str = substr($str,1);
$sql = "UPDATE upload set pic = '".$str."' WHERE id = ".$uid;
$result = $mysqli->query($sql);

這裏我有不少的判斷沒有寫,主要是實現一下功能,好比文件夾要先創建好,你也能夠本身判斷,不存在就建立一個文件夾,還有一些其餘判斷等等。

最關鍵的地方是,當你不熟悉的時候,要走一步調試一步,看獲得的結果是什麼。

圖片現實功能

 

<?php
require_once 'connection.php';
$uid = 1;
$sql = "SELECT pic FROM upload WHERE id =".$uid;
$result = $mysqli->query($sql);
//取出第一個圖片的地址
$picpath = '';
while ($row = $result->fetch_array()){
    $picpath = $row[0];
}
$picpath = explode(',',$picpath)[0];

echo "<img src='".$picpath."'>";
?>

相關文章
相關標籤/搜索