Отправка двух DropZones вместе с Ajax - PullRequest
1 голос
/ 04 августа 2020

У меня есть форма, которую мне нужно отправить, а также две зоны перетаскивания, у меня нет проблем с отправкой их по отдельности, но я хотел бы отправить их все как одно целое.

HTML:

image

Javascript:

    dropzone.autoDiscover = false;
var image_width = 380, image_height = 507;
var photo_upload_primary = new Dropzone("#photo_upload_primary",{
    maxFilesize: 1,
    maxFiles: 1,
    acceptedFiles: "image/*",
    autoProcessQueue: false,
    url: "upload.php",
    previewsContainer: "#formfiles",
    previewTemplate: $("#formtemplate").html(),
    dictFileTooBig: "Image is too large ({{filesize}}MiB). Max file size is {{maxFilesize}}MiB.",
    dictInvalidFileType: "This file is not an image.",
    dictMaxFilesExceeded: "You have already uploaded a primary product image.",
    dictDefaultMessage: "Click or drop primary product image here",
    success: function (file, response) {
        console.log(response);
    },
    error: function (file, response) {
        $.notify({
             message: response
        },{
            type: "danger"
        });    

        this.removeFile(file); 
    },
    init: function() {
        this.on("thumbnail", function(file) {
            if (file.width !== image_width || file.height !== image_height) {
                file.rejectDimensions();
            }
            else {
                file.acceptDimensions();
            }
        });
    },
    accept: function(file, done) {
            file.acceptDimensions = done;
            file.rejectDimensions = function() {
                done("Product image resolution outside of specifications. Resolution must be "+image_width+"px x "+image_height+"px");
            };
    },
        renameFile: function (file) {
        var ext = file.name.substring(file.name.lastIndexOf('.')+1);
        var newName = 'primary.' + ext;
        return newName;
    },
});

var photo_upload_secondary = new Dropzone("#photo_upload_secondary",{
    maxFilesize: 1,
    maxFiles: 1,
    acceptedFiles: "image/*",
    autoProcessQueue: false,
    url: "upload.php",
    previewsContainer: "#formfiles",
    previewTemplate: $("#formtemplate").html(),
    dictFileTooBig: "Image is too large ({{filesize}}MiB). Max file size is {{maxFilesize}}MiB.",
    dictInvalidFileType: "This file is not an image.",
    dictMaxFilesExceeded: "You have already uploaded a secondary product image.",
    dictDefaultMessage: "Click or drop secondary product image here",
    success: function (file, response) {
        console.log(response);
    },
    error: function (file, response) {
        $.notify({
             message: response
        },{
            type: "danger"
        });
        this.removeFile(file); 
    },
    init: function() {

        this.on("thumbnail", function(file) {
            if (file.width !== image_width || file.height !== image_height) {
                file.rejectDimensions();
            }
            else {
                file.acceptDimensions();
            }
        });
    },
    accept: function(file, done) {
            file.acceptDimensions = done;
            file.rejectDimensions = function() {
                done("Product image resolution outside of specifications. Resolution must be "+image_width+"px x "+image_height+"px");
            };
    },
    renameFile: function (file) {
        var ext = file.name.substring(file.name.lastIndexOf('.')+1);
        var newName = 'secondary.' + ext;
        return newName;
    }
});


function upload(){

    photo_upload_primary.processQueue();
    photo_upload_secondary.processQueue();
}


$('#add-product-form').submit(function (e) {
    e.preventDefault();
    var $form = $(this);

    if (!$form.valid) return false;

    if (photo_upload_primary.getQueuedFiles().length == 0) {
        $.notify({
             message: "Please upload a primary product photo."
        },{
            type: "danger"
        });
        return false;
    }
    if (photo_upload_secondary.getQueuedFiles().length == 0) {
        $.notify({
             message: "Please upload a secondary product photo."
        },{
            type: "danger"
        });
        return false;
    }

    addproduct();
  
});


function addproduct(){
    var datafeilds = Array.from(document.querySelectorAll("[id^='add-product-']"));
    var data = {};
    datafeilds.forEach(function(field){
        let replace = field.id.replace("add-product-", "");
        data[replace] = field.value;
    });
    $.ajax({
        type: 'POST',
        url: 'addproduct-pdo.php',
        data: {data: data},
        dataType: 'json', 
        success: function(data) {

            $.notify({
                message: data.message
            },{
                type: data.response
            });

            if (data.response == "success"){
                $("#add-product-form").trigger('reset');
                photo_upload_primary.removeAllFiles(); 
                photo_upload_secondary.removeAllFiles();   
            }
        }
    });
}

PHP (выгрузка. php):

$ds = DIRECTORY_SEPARATOR;
$foldername = "./uploads";

if (!empty($_FILES)) {
    $fileupload = basename( $_FILES['file']['name']);
    $fileType = $_FILES['file']['type'];
    $fileSize = $_FILES['file']['size'];
    $tempFile = $_FILES['file']['tmp_name'];
    $targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
    $targetFile =  $targetPath.$fileupload;
    move_uploaded_file($tempFile,$targetFile);

    echo "File uploaded";
}

PHP (addproduct-pdo. php):

    try {
    $options = [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
    \PDO::ATTR_EMULATE_PREPARES => false,
    ];
    $conn = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);

    function escape_mysql_identifier($field){
        return "`".str_replace("`", "``", $field)."`";
    }

    function prepared_insert($pdo, $table, $data) {
        $keys = array_keys($data);
        $keys = array_map('escape_mysql_identifier', $keys);
        $fields = implode(",", $keys);
        $table = escape_mysql_identifier($table);
        $placeholders = str_repeat('?,', count($keys) - 1) . '?';
        $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
        $pdo->prepare($sql)->execute(array_values($data));
    }

    $data = array_filter($data);

    prepared_insert($conn, 'products', $data);

    $id = $conn->lastInsertId();

    if ($id > 1) {
        echo json_encode(array('response'=>'success','message'=>'Product successfully added as ID # '.$id));
    }else{
        echo json_encode(array('response'=>'danger','message'=>'Product not successfully added'));
    }

}catch(PDOException $e){
    
    echo json_encode(array('response'=>'danger','message'=>$e->getMessage()));
}
    $conn = null;

У меня проблемы с двумя вещами:

  1. Как я могу отправить обе DropZone как одну?
  2. Как я могу отправить DropZone (ы) с Ajax? Мне нужно будет передать $id из addproduct-pdo. php либо в DropZone Javascript, либо загрузить. php, чтобы он правильно назвал файл.

Спасибо!

...