首页 > 解决方案 > 在javascript中上传拖动的图像?

问题描述

所以,我在php中制作了一个上传系统,在你可以选择图像之前。现在,您可以选择图像或将图像拖到上传系统上。我遇到的问题,如果我选择和图像然后上传它,它工作正常并且图像的名称在上传之前显示但是当我拖动图像时显示名称但我似乎无法上传它. 无论如何要解决我遇到的这个问题,我不知道如何解决它。

HTML:
<div class="container">
        <div class="add-form">
            <h1 class="text-center"><font face="fantasy" size = "10"><center>Please Insert new image</center></font></h1>
            <form method="post" enctype="multipart/form-data" id="FormID" onsubmit="uploadFiles(event)">
                <label for = "name" id = "LabelName"><font face = fantasy size = "5">
                <img src = "https://image.flaticon.com/icons/png/512/1233/1233986.png" width = "50">
                 <br>
                 UserName</font></label>
                <input class = "UsernameUpload" id = "name" type="text" name="user_name" class="form-control">

                <label for = "image" id = "fileLabel"
                ondragover = "overrideDefault(event);fileHover();"
                ondragenter = "overrideDefault(event);fileHover();"
                ondragleave = "overrideDefault(event);fileHoverEnd();"
                ondrop = "overrideDefault(event);fileHoverEnd();addFiles(event);">



                <font face = "fantasy" size = "5">
                <img src = "https://image.flaticon.com/icons/png/512/1180/premium/1180674.png" width = "50">
                 <br>

                 <span id = "fileLabelText">Select image to upload Or Drag N Drop</font></span>
                 <br>
                 </label>

                <input multiple onchange = "addFiles(event)" id = "image" type="file"  onchange ="unlock()" name="profile" class="form-control2" accept="*/image">
                <button class = "uploadButton" type="submit" value = "submit" name="btn-add" onClick = "return validate()" action = "index.php"><font face = "calibri" size = "4">upload</font></button>
                <div id = "error"><font face = "fantasy">Please fill up the username and select and image</font></div>


            </form>
        </div>
        <hr style="border-bottom: 5px blue solid;">
    </div> 

CSS代码:

<style type = "text/css">

body{
    background-color: lightblue;
}

#FormID {
  margin: 16px;
  text-align: center;
  border-radius: 8px;
  overflow: hidden;
  transition: 0.5s;
}

#FormID #fileLabel {
  background-color: rgba(0, 255, 0, 0.5);
  display: block;
  padding: 16px;
  position: relative;
  cursor: pointer;
}

#FormID #image {
  display: none;
}

#FormID #fileLabel:after,
#FormID #fileLabel:before {
  position: absolute;
  content: "";
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: -2;
  border-radius: 8px 8px 0 0;
}

#FormID #fileLabel:before {
  z-index: -1;
  background: repeating-linear-gradient(
    45deg,
    transparent,
    transparent 5%,
    black 5%,
    black 10%
  );
  opacity: 0;
  transition: 0.5s;
}

#FormID.fileHover #fileLabel:before {
  opacity: 0.25;
}

#FormID .uploadButton {
  border: 0;
  outline: 0;
  width: 100%;
  padding: 8px;
  background-color: limeGreen;
  color: #fff;
  cursor: pointer;
}

#FormID.fileHover {
  box-shadow: 0 0 16px limeGreen;
}

Javascript代码:

<script>

function validate()
{

    var username = document.getElementById("name");
    var img = document.getElementById("image");


    if(username.value.trim()=="") {
        var myDiv = document.getElementById("error");
        username.style.border = "solid 3px red";
        myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">username not entered</font>';
        return false;
    }
    else if (username.value.length<8){
        var myDiv = document.getElementById("error");
        username.style.border = "solid 3px red";
        myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">username need to be atleast 8 characters long</font>';
        return false;
    }
    else if (img.value.trim()=="") {
        var myDiv = document.getElementById("error");
        img.style.border = "solid 3px red";
        myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">Please Select an image</font>';
        return false;
    }


}
var FormID = document.getElementById("FormID");
var fileLabelText = document.getElementById("fileLabelText");
var uploadStatus = document.getElementById("uploadStatus");
var image = document.getElementById("image");
var droppedFiles;

function overrideDefault(event) {
  event.preventDefault();
  event.stopPropagation();
}

function fileHover() {
  FormID.classList.add("fileHover");
}

function fileHoverEnd() {
  FormID.classList.remove("fileHover");
}

function addFiles(event) {
  droppedFiles = event.target.files || event.dataTransfer.files;
  showFiles(droppedFiles);
}

function showFiles(files) {
  if (files.length > 1) {
    fileLabelText.innerText = files.length + " files selected";
  } else {
    fileLabelText.innerText = files[0].name;
  }
}

</script>

编辑:这也是 PHP 代码:

<?php 
    include("config.php");
    if(isset($_GET['delete_id']))
    {
        $stmt_select=$db_conn->prepare('SELECT * FROM tbl_user WHERE id=:uid');
        $stmt_select->execute(array(':uid'=>$_GET['delete_id']));
        $imgRow=$stmt_select->fetch(PDO::FETCH_ASSOC);
        unlink("uploads/".$imgRow['picprofile']);
        $stmt_delete=$db_conn->prepare('DELETE FROM tbl_user WHERE id =:uid');
        $stmt_delete->bindParam(':uid', $_GET['delete_id']);
        if($stmt_delete->execute())
        {
            ?>
            <script>

            window.location.href=('index.php');
            </script>
            <?php 
        }else

        ?>
            <script>

            window.location.href=('index.php');
            </script>
            <?php 

    }

    ?>

<?php 

    if(isset($_POST['btn-add']))
    {
        $name=$_POST['user_name'];
        $images=$_FILES['profile']['name'];
        $path = "uploads/";
        $rand=rand(1000, 1000000);
        $filename = "$rand.jpg";
        $filepath = "$path$filename";

                function correctImageOrientation($filename) {
  if (function_exists('exif_read_data')) {
    $exif = exif_read_data($filename);
    if($exif && isset($exif['Orientation'])) {
      $orientation = $exif['Orientation'];
      if($orientation != 1){
        $img = imagecreatefromjpeg($filename);
        $deg = 0;
        switch ($orientation) {
          case 3:
            $deg = 180;
            break;
          case 6:
            $deg = 270;
            break;
          case 8:
            $deg = 90;
            break;
        }
        if ($deg) {
          $img = imagerotate($img, $deg, 0);        
        }
        // then rewrite the rotated image back to the disk as $filename 
        imagejpeg($img, $filename, 95);
      } // if there is some rotation necessary
    } // if have the exif orientation info
  } // if function exists      
}

        $imgExt=strtolower(pathinfo($images,PATHINFO_EXTENSION));
        if (move_uploaded_file($_FILES["profile"]["tmp_name"], $filepath)){ 
            $images = imagecreatefromjpeg($filepath);       
        }

         correctImageOrientation($filepath);


        if ($imgExt == "jpeg" || $imgExt == "jpg") {
            $im = imagecreatefromjpeg($filepath);
        }else if($imgExt == "png"){
            $im = imagecreatefrompng($filepath);
        }else if($imgExt == "gif"){
            $im = imagecreatefromgif($filepath);
        }
        $size = getimagesize($filepath);

             $width = imagesx($im);
             $height = imagesy($im);
             $newwidth= 800;
             $newheight= 800;



                if(($width/$newwidth) < ($height/$newheight)){
                    $y = 0;
                    $x = $width - (($height * $newwidth) / $newheight);
                }else{
                    $x = 0;
                    $y = $height - (($width * $newheight) / $newwidth);
                }


             $virtual_image = imagecreatetruecolor(850, 850);    
             imagealphablending($virtual_image, true);
             imagesavealpha($virtual_image, true);

             imagecopyresampled($virtual_image,$im,0,0, $x/2, $y/2, $newwidth, $newheight, $width-$x, $height-$y); 
             $bgcolor = imagecolorallocatealpha($virtual_image,255,255,255,127);


             imagefill($virtual_image,0,0,$bgcolor);

             imagecolortransparent($virtual_image, $bgcolor);


             imagejpeg($virtual_image,$filepath,100);



            $stmt=$db_conn->prepare('INSERT INTO tbl_user(username, picprofile) VALUES (:uname, :upic)');
            $stmt->bindParam(':uname', $name);
            $stmt->bindParam(':upic', $filename);
            if($stmt->execute())
        {
            echo "Uploaded";
            header("Location:index.php");

        }else

        {
            ?>
            <script>
                alert("Error");
                window.location.href=('index.php');
            </script>
        <?php
        }

    }
?>

标签: javascripthtmlcss

解决方案


推荐阅读