简体   繁体   中英

How to create a unique name for each image and upload

I have a folder named uploads where when click submit, the user images are uploaded inside that folder and the images is previewed when upload complets.

If there is two images with same name , then former get replaced. I would like to create unique name for each image thus both image could be saved.

Here is my index code

 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script> <script type="text/javascript" src="jquery.form.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#submitButton').click(function () { $('#uploadForm').ajaxForm({ target: '#outputImage', url: 'uploadFile.php', beforeSubmit: function () { $("#outputImage").hide(); if($("#uploadImage").val() == "") { $("#outputImage").show(); $("#outputImage").html("<div class='error'>Choose a file to upload.</div>"); return false; } $("#progressDivId").css("display", "block"); var percentValue = '0%'; $('#progressBar').width(percentValue); $('#percent').html(percentValue); }, uploadProgress: function (event, position, total, percentComplete) { var percentValue = percentComplete + '%'; $("#progressBar").animate({ width: '' + percentValue + '' }, { duration: 5000, easing: "linear", step: function (x) { percentText = Math.round(x * 100 / percentComplete); $("#percent").text(percentText + "%"); if(percentText == "100") { $("#outputImage").show(); } } }); }, error: function (response, status, e) { alert('Oops something went.'); }, complete: function (xhr) { if (xhr.responseText && xhr.responseText != "error") { $("#outputImage").html(xhr.responseText); } else{ $("#outputImage").show(); $("#outputImage").html("<div class='error'>Problem in uploading file.</div>"); $("#progressBar").stop(); } } }); }); }); </script> </head> <body> <h1>jQuery Ajax Image Upload with Animating Progress Bar</h1> <div class="form-container"> <form action="uploadFile.php" id="uploadForm" name="frmupload" method="post" enctype="multipart/form-data"> <input type="file" id="uploadImage" name="uploadImage" /> <input id="submitButton" type="submit" name='btnSubmit' value="Submit Image" /> </form> <div class='progress' id="progressDivId"> <div class='progress-bar' id='progressBar'></div> <div class='percent' id='percent'>0%</div> </div> <div style="height: 10px;"></div> <div id='outputImage'></div> </div> </body> </html>

and my upload.php is

 <?php if (isset($_POST['btnSubmit'])) { $uploadfile = $_FILES["uploadImage"]["tmp_name"]; $folderPath = "uploads/"; if (! is_writable($folderPath) || ! is_dir($folderPath)) { echo "error"; exit(); } if (move_uploaded_file($_FILES["uploadImage"]["tmp_name"], $folderPath . $_FILES["uploadImage"]["name"])) { echo '<img src="' . $folderPath . "" . $_FILES["uploadImage"]["name"] . '">'; exit(); } } ?>

Thanks in advance.

I've added function makeFilenameUniq() that is generating unique filename in upload target folder using uploaded filename.

You can change algoritm of generating an unique key in function uniqKey() .

<?php
function makeFilenameUniq($pathfile)
{
    $test = $pathfile;
    while (is_readable($test)) {
        $uniqKey = makeUniqKey();
        if (preg_match('/^(.+)\.(.+?)$/', $pathfile, $m)) {
            $test = $m[1] . "-{$uniqKey}." . $m[2];
        } else {
            $test = $pathfile . "-{$uniqKey}";
        }
    }
    return $test;
}

function makeUniqKey()
{
    return base_convert(mt_rand(0, 10000), 10, 32);
}

if (isset($_POST['btnSubmit'])) {
    $uploadfile = $_FILES["uploadImage"]["tmp_name"];
    $folderPath = "uploads/";

    if (!is_writable($folderPath) || ! is_dir($folderPath)) {
        echo "error";
        exit();
    }
    $pathfile = makeFilenameUniq($folderPath . $_FILES["uploadImage"]["name"]);
    if (move_uploaded_file($_FILES["uploadImage"]["tmp_name"], $pathfile)) {
        echo "<img src=\"${pathfile}\">";
        exit();
    }
}

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