简体   繁体   中英

Upload text along with image through form

Using dropzone.js i am trying to create drag and drop feature to upload images.

Code on form page

<script type="text/javascript" src="js/dropzone.js"></script>
<form action="upload.php" class="dropzone">
</form>

upload.php

<?php
if(!empty($_FILES))
  {
    $targetDir = "uploads/";
    $fileName = $_FILES['file']['name'];
    $targetFile = $targetDir.$fileName;

    if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile))
      {
         $conn->query("INSERT INTO files (file_name) VALUES('".$fileName."')");
      }
  }
?>

The above code uploads the image as soon as i drop the image, but i also wish to input following details in the form and on click of submit button it should get saved in database along with image

<input type="text" name="title"  value="Title" />
<textarea name="text" ></textarea>
<input type="text" name="email"  value="Email" />
<input type="submit" name="edit" alt="edit" value="Submit"/>

Can anyone tell how it can be done

Edited:

I'm requiring you to download jQuery first here .

Then, we have to call it along side your dropzone.js :

<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script type="text/javascript" src="js/dropzone.js"></script>

You can include your other fields inside your form, or outside, not important with the path we will take later. Notice that we add id tags for your other input fields:

<form action="upload.php" class="dropzone" enctype="multipart/form-data">
    <input type="text" name="title" id="title" value="Title" />
    <textarea name="text" id="description"></textarea>
    <input type="text" name="email" value="Email" id="email" />
    <input type="submit" name="edit" alt="edit" value="Submit"/>
</form>

Then, lets create a script for your dropzone and an Ajax which will run if the file you try to upload has met the requirements of your dropzone:

$(document).ready(function(){

    $(".dz-default").hide(200); /* THIS WILL HIDE FIRST THE UPLOAD FIELD */

    function insert(filename){ /* CREATE A FUNCTION THAT WILL INSERT THE DATA */

        /* GET THE INPUT DATA OF THE USER */
        var title = $("#this").val(),
            desc = $("#description").val(),
            email = $("#email").val();

        $.ajax({ /* START AJAX */
            url: "upload.php", /* FILE TO BE SUBMITTED THE DATA */
            type: "POST", /* METHOD TO PASS THE DATA */
            data: {'title': title, 'desc': desc, 'email': email, 'filename': filename} /* DATA TO BE PASSED TO upload.php */
        });
    }

    $(document).on("change keyup", "input", function(){ /* IF USER IS TRYING TO PUT DATA TO THE TEXT FIELDS */

        /* GET ALL USER'S INPUT */
        var title = $("#this").val(),
            desc = $("#description").val(),
            email = $("#email").val();

        if(title != '' && desc != '' && email != ''){ /* IF ALL INPUT HAS BEEN FILLED */
            $(".dz-default").show(200); /* SHOW THE UPLOAD FIELD */
        } else {
            $(".dz-default").hide(200); /* HIDE THE UPLOAD FIELD */
        }
    });

    Dropzone.options.myAwesomeDropzone = { /* WHEN USER UPLOAD A FILE */
        paramName: "file", // The name that will be used to transfer the file
        maxFilesize: 2, // MB
        accept: function(file, done) {
            insert(file.name); /* CALL OUR FUNCTION THAT INSERTS INPUT DATA WITH THE FILE NAME AS OUR PARAMETER */
        }
    };

});

Then for your upload.php :

if(!empty($_FILES)){ /* MOVE FILE TO YOUR PREFERRED DIRECTORY */

    $targetDir = "uploads/";
    $fileName = $_FILES['file']['name'];
    $targetFile = $targetDir.$fileName;

    move_uploaded_file($_FILES['file']['tmp_name'], $targetFile);

}

/* INSERT DATA TO YOUR DATABASE */
if(!empty($_POST["title"]) && !empty($_POST["desc"]) && !empty($_POST["email"]) && !empty($_POST["filename"])){

    /* USE AT LEAST REAL_ESCAPE_STRING BEFORE INSERTING THEM TO YOUR DATABASE */
    $title = $conn->real_escape_string($_POST["title"]);
    $desc = $conn->real_escape_string($_POST["desc"]);
    $email = $conn->real_escape_string($_POST["email"]);
    $filename = $conn->real_escape_string($_POST["filename"]);

    $conn->query("INSERT INTO files (title, description, email, file_name) VALUES('$title', '$desc', '$email', '$fileName')");

}

The only problem with this is that the user must put first their information before uploading the file. Made a solution by hiding first the upload field then will only show up after filling up all the text fields.

To avoid uploading image as soon as you drop the image, you can use following code.

Dropzone.autoDiscover = false;

var myDropzone = new Dropzone(element, {
     url: "/upload.php",                        
     autoProcessQueue: false,
});

$('#imgsubbutt').click(function(){           
     myDropzone.processQueue();
});

You can send extra data using "on sending" event.

myDropzone.on("sending", function(file, xhr, formData) {

  formData.append("text", "sample text");
});

OR you can save file on temporary location after drop. Then submit your form as usual. On server side file can be moved from temporary location to final location and then delete temporary location file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM