简体   繁体   中英

Uploading multiple images with dropzone.js with PHP

I am building a simple image upload with dropzone.js . Everything is working when I upload a single image, however, when I try dropping and uploading multiple images at once the upload behaves strangely. Sometimes it uploads a couple images while ignoring the others. And sometimes it doesn't upload any. I was under the impression that dropzone sends a seperate post for each file when uploading multiple files according to its documentation so I can't figure out if this is a PHP issue or dropzone related.

Here is what I have so far:

HTML:

<form id="dzone" action="upload.php" class="dropzone">

    <p class="dz-message"><span>Drop images here or click to upload.</span><br />
    <span class="note">Only images with the following file types are allowed <strong>(jpg , jpeg , png , bmp)</strong></span></p>

    <!-- no-script fallback -->
    <div class="fallback">
        <input name="file" type="file" multiple />
    </div>

</form>

JS:

Dropzone.options.dzone = {
    acceptedFiles: "image/*",
    maxFilesize: 20,
    parallelUploads: 3
};

PHP:

$ds = DIRECTORY_SEPARATOR; 

$upload_location = 'uploads';

if(!empty($_FILES)) {

    $temp_file = $_FILES['file']['tmp_name'];

    // Check if uploaded file is an image
    if(!is_valid_type($temp_file)) {
        echo '<p>only images are allowed</p>';
        exit;
    }

    $temp_name = explode('.' , $_FILES['file']['name']);
    $target_path = dirname(__FILE__) . $ds . $upload_location . $ds;
    $new_file_name = round(microtime(true)) . '.' . end($temp_name);
    $target_file = $target_path . $new_file_name;

    move_uploaded_file($temp_file , $target_file);

    // Change file permission to read only
    chmod($target_file, 0644);
}

function is_valid_type($file) {

    // Image Size
    $size = getimagesize($file);
    if(!$size) {
        return 0;
    }

    // Valid file types
    $valid_types = array(IMAGETYPE_GIF , IMAGETYPE_JPEG , IMAGETYPE_PNG , IMAGETYPE_BMP);

    if(in_array($size[2] , $valid_types)) {
        return 1;
    } else {
        return 0;
    }
}

I have tried altering the PHP form engine to process each file in a foreach loop, but it results with the same issue. Am I missing something?

here is the correct code that solves your question!

Change this at your upload.php file:

change string:

round(microtime(true))

to:

round(microtime(true)) + rand()

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