如何为每个图像创建唯一的名称并上传

时间:2019-02-03 04:44:17

标签: php

我有一个名为uploads的文件夹,单击提交时,该文件夹中将上传用户图像,并在上传完成时预览这些图像。

如果有两个具有相同名称的图像,则替换前一个。我想为每个图像创建唯一的名称,以便可以保存两个图像。

这是我的索引代码

<!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>

我的upload.php是

<?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();
    }
}
?>

谢谢。

1 个答案:

答案 0 :(得分:1)

我添加了功能makeFilenameUniq(),该功能使用上传的文件名在上传目标文件夹中生成唯一的文件名。

您可以在函数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();
    }
}