代码之家  ›  专栏  ›  技术社区  ›  Nandini Srivastava

输入标签未在某些设备中选择多个图像

  •  0
  • Nandini Srivastava  · 技术社区  · 1 年前

    我创建了一个网站,用户可以在这里上传带有图片的问题。为此,我使用带有“multiple”属性的input标记来选择多个图像,并使用PHP将其上传到数据库中。但在一些设备或可能是浏览器中,它不会选择多个图像或将其存储在数据库中。在这些设备中,它只存储单个图像。 我正在提供我的输入标签代码。如果你需要,我可以提供完整的网页代码与数据库连接代码。

    你能告诉我解决办法吗。

    <input type="file" accept="image/png , image/jpeg" multiple id="quesImgSelect" onchange="quesPreview()" class="imgBtn" name="quesDoc[]">
    

    尝试上载多个图像,但在某些设备上不起作用。

    我页面的完整代码在这里。。。。。。

    session_start();
    //include "config.php";
    
    ?>
    <!-- Uploading code starts -->
    
    <?php
    include "config.php";
    if(isset($_POST["submit"])){
      // print_r("expression");exit()
    if (empty($_FILES['ansDoc']['name'][0])) {
    
    $ansImgText = "no" ;
    }else{
       
    $ansImgText = "yes" ; 
      
      };
    
    
      if (empty($_FILES['quesDoc']['name'][0])) {
    
        $quesImgText = "no" ;
        }else{
           
        $quesImgText = "yes" ; 
          
          };
    
    
      $userId = $_SESSION['id'];
    
    $question ="no" ;
    $exam =$_GET['exam'] ;
    $year =$_GET['year'] ;
    $ansText =(mysqli_real_escape_string($conn,$_POST['ansText'])) ;
    $quesText =(mysqli_real_escape_string($conn,$_POST['quesText'])) ;
    $subject =(mysqli_real_escape_string($conn,$_POST['sub'])) ;
    $lang =(mysqli_real_escape_string($conn,$_POST['lang'])) ;
    if($_POST['lang'] == ""){
        $topic ="no" ;
    }else{
        $topic =(mysqli_real_escape_string($conn,$_POST['topic'])) ;
    }
    
    $approval ="no" ;
    $solution ="no" ;
    $paperId =$_GET['id'] ;
    
    //echo $paperId.$year;
    date_default_timezone_set('Asia/Kolkata');
    $date=date("y-m-d");
    
    $sql="INSERT INTO `questions` (`question`, `userId`, `date`, `subject`, `lang`, `topic`, `approval`, `solution`, `exam`, `year`, `paperId`,`quesImg`,`ansImg`) VALUES    
    ('{$quesText}', '{$userId}', '{$date}','{$subject}','{$lang}', '{$topic}','{$approval}','{$ansText}','{$exam}','{$year}','{$paperId}','{$quesImgText}','{$ansImgText}')";
     
    $result=mysqli_query($conn,$sql) or die("result failed1");
    
      
     $idd= $conn->insert_id; 
    
    //echo $idd;
    
    // print_r($_FILES['quesDoc']);exit();
    
    foreach($_FILES['quesDoc']['name'] as $key=>$val){
        
    $filename = rand().".jpg";
    // 3,000,000
    // print_r($_FILES['quesDoc']['size'][$key]);exit();
    $file_size = $_FILES['quesDoc']['size'][$key];
    //if($file_size < 3000000){
    move_uploaded_file($_FILES['quesDoc']['tmp_name'][$key],"quesImg/".$filename);
    
    $sql2="INSERT INTO `quesimg` (`qId`, `image`,`paperId`) VALUES ('{$idd}','{$filename}','{$paperId}')";
    
    $result2=mysqli_query($conn,$sql2) or die("result failed2");
    //}
       // echo "Error: " . mysqli_error($conn);
    
    //echo "added";
    }
    
    //if (!empty($_FILES['ansDoc']['name'][0])) {
    
    foreach($_FILES['ansDoc']['name'] as $key=>$val){
        
        $filename2 = rand().".jpg";
        move_uploaded_file($_FILES['ansDoc']['tmp_name'][$key],"ansImg/".$filename2);
        
        $sql3="INSERT INTO `solutionimg` (`qId`, `image`,`paperId`) VALUES ('{$idd}','{$filename2}','{$paperId}')";
        
        $result3=mysqli_query($conn,$sql3) or die("result failed3");
        
           // echo "Error: " . mysqli_error($conn);
        
       // echo "added";
    
      //  $id = mysqli_real_escape_string($conn,$_POST['id']);
    
    $sql4 = "SELECT * FROM `question_paper` WHERE `id` = $paperId";
    $result4=mysqli_query($conn,$sql4) or die("result failed4");
    if(mysqli_num_rows($result4)>0){
        while($row=mysqli_fetch_assoc($result4)){
           $total = $row['total'] ;
           $newTotal = $total + 1;
            
           // echo $newRented;
        $sql5="UPDATE `question_paper` SET `total` = $newTotal  WHERE `question_paper`.`id` = $paperId";
    
       
        $result5=mysqli_query($conn,$sql5) or die("result failed5"); 
              
       // echo "updated";
        }
    
    
        
        
    }
    
    
    $sql6 = "SELECT * FROM `ZZZ_teacherProfile` WHERE `id` = $userId";
    $result6=mysqli_query($conn,$sql6) or die("result failed");
    if(mysqli_num_rows($result6)>0){
        while($row=mysqli_fetch_assoc($result6)){
           $total = $row['ques'] ;
           $newTotal = $total + 1;
            
           // echo $newRented;
        $sql7="UPDATE `ZZZ_teacherProfile` SET `ques` = $newTotal  WHERE `ZZZ_teacherProfile`.`id` = $userId";
    
       
        $result7=mysqli_query($conn,$sql7) or die("result failed6"); 
              
       // echo "updated";
        }
    
    
        
        
    }
    
    
    
    
        echo "<script>";
        echo  "alert('Question added successfully.')";
          echo  "</script>";
    
        }
    
    
    }
    ?>
    
    <!-- Uploading code ends -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Add question</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="addQuestionPage.css">
    
        
    <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    </head>
    <body>
    <div id="container">
    
    
    <div id="backBtnContainer">
        <a href="adminPaperDetailPage.php?id=<?php echo $_GET['id'];?>">Back</a>
    </div>
            
            <form  action="<?php $_SERVER['PHP_SELF'] ?>" method="POST" id="form" enctype="multipart/form-data">
    
    
            <label for="language">Select language</label>
    
            <select name="lang" id="language">
    <option value="english">English</option>
        <option value="hindi">Hindi</option>
    
    </select>
    
    <label for="subjectsDropdown">Select subject</label>
      <select id="subjectsDropdown" onchange="loadTopics()" name="sub">
    
      <?php
        include "config.php";
      
           $sql="SELECT * FROM `$db`.`ZZ_subject` ORDER BY `name` ASC";
           $result=mysqli_query($conn,$sql);
       
           if(mysqli_num_rows($result)>0){
               while($row=mysqli_fetch_array($result)){
                   $data['id']=$row['0'];
                $data['subject']= $row['1'];
              
                ?>
             
            <option value="<?php   echo $row['name'];  ?>"> <?php   echo $row['name'];  ?></option>
    
      <?php
               }
    
              
            }else{ 
                echo "No category added";
    
            }
            ?>
     
    </select>
    <label for="topicsDropdown">Select topic</label>
    
    <!-- Second Dropdown (Topics) -->
    <select id="topicsDropdown" name="topic">
     
    </select>
    
    
    <textarea rows="10"  placeholder="Enter question" class="inputBox" id="quesText" name="quesText"></textarea>
    <input type="file" accept="image/*" multiple id="quesImgSelect" onchange="quesPreview()" class="imgBtn" name="quesDoc[]">
    <label for="quesImgSelect" class="ImgLabel"> <i class="fa fa-upload" aria-hidden="true"></i> Upload question image Should be less than 3mb </label>
    <p id="quesImgCount" >No file choosen</p>
    <div id="quesImage" class="imgDiv"></div>
    
    <textarea rows="10" cols="60" placeholder="Enter answer" class="inputBox" id="answerText" name="ansText"></textarea>
    <input type="file" accept="image/png , image/jpeg" multiple="multiple" id="ansImageSelect" class="imgBtn" onchange="ansPreview()" name="ansDoc[]">
    <label for="ansImageSelect" class="ImgLabel"> <i class="fa fa-upload" aria-hidden="true"></i> Upload answer image Should be less than 3mb</label>
    
    <p id="ansImgCount" >No file choosen</p>
    <div id="ansImage" class="imgDiv"></div>
    
    <input type="submit" value="SAVE" id="submit" name="submit">
    
    
    
    </form>
    
    
    
    <script>
    function loadTopics() {
      // Get the selected subject from the first dropdown
      let selectedSubject = document.getElementById("subjectsDropdown").value;
    
      // Get the second dropdown element
      let topicsDropdown = document.getElementById("topicsDropdown");
    
      // Clear the existing options in the second dropdown
      topicsDropdown.innerHTML ;
    
      // Use AJAX to fetch topics for the selected subject from the database
      // You can use any AJAX library like jQuery or fetch API
      fetch('G_getTopic.php?subject_id=' + selectedSubject)
        .then(response => response.json())
        .then(data => {
            topicsDropdown.innerHTML = '';
          // Check if there are topics available for the selected subject
          if (data.length > 0) {
            data.forEach(topic => {
              addTopicOption(topic.topic_name, topic.topic_name);
            });
          } else {
            addTopicOption('no', 'No topic added');
          }
        })
        .catch(error => {
          console.error('Error fetching topics: ', error);
        });
    }
    
    // Helper function to add options to the second dropdown
    function addTopicOption(value, text) {
      let topicsDropdown = document.getElementById("topicsDropdown");
      let option = document.createElement("option");
      option.value = value;
      option.text = text;
      topicsDropdown.appendChild(option);
    }
    
    
    //Images code ---------------------------------------------------------------
    
    
    let quesInput = document.getElementById("quesImgSelect");
    let ansInput = document.getElementById("ansImageSelect");
    
    let quesCountView = document.getElementById("quesImgCount");
    let ansCountView = document.getElementById("ansImgCount");
    
    let quesImageDiv = document.getElementById("quesImage");
    let ansImageDiv = document.getElementById("ansImage");
    
    
    function quesPreview(){
        quesCountView.textContent = `${quesInput.files.length} Files selected`;
    
        for(i of quesInput.files){
            let reader = new FileReader();
            let figure = document.createElement("figure");
            let figCap = document.createElement("figCaption");
    
            figCap.innerText = i.name;
            figure.appendChild(figCap);
            reader.onload=()=>{
                let img = document.createElement("img");
                img.setAttribute("src",reader.result);
                figure.insertBefore(img,figCap);
            }
            quesImageDiv.appendChild(figure);
            reader.readAsDataURL(i);
        }
    }
    
    
    function ansPreview(){
        ansCountView.textContent = `${ansInput.files.length} Files selected`;
    
        for(i of ansInput.files){
            let reader = new FileReader();
            let figure = document.createElement("figure");
            let figCap = document.createElement("figCaption");
    
            figCap.innerText = i.name;
            figure.appendChild(figCap);
            reader.onload=()=>{
                let img = document.createElement("img");
                img.setAttribute("src",reader.result);
                figure.insertBefore(img,figCap);
            }
            ansImageDiv.appendChild(figure);
            reader.readAsDataURL(i);
        }
    }
    </script>
    
    </div>
    </body>
    </html>```
    
    0 回复  |  直到 1 年前
    推荐文章