接受上传的同名文件?

时间:2015-10-02 00:52:18

标签: php html css forms file-upload

我有一个人们可以上传单个图片的表单。大多数人都是从他们的移动设备上传图片。每个拥有iPhone的人都将其图片上传为“image.png”。我需要让我的表单不要拒绝它,并且只接受具有相同名称的文件而不删除旧文件,或者将它们重命名为“imageupload1.png”,“imageupload2.png”或甚至是image.png然后“image-Copy”。 png“then”image-Copy(2).png“等等

我觉得这样的事情可能有用:

$filename = $_FILES['myfilename']['name'];
$filename = time().$filename;

 function renameDuplicates($path, $file)
{   
    $fileName = pathinfo($path . $file, PATHINFO_FILENAME);
    $fileExtension = "." . pathinfo($path . $file, PATHINFO_EXTENSION);

    $returnValue = $fileName . $fileExtension;

    $copy = 1;
    while(file_exists($path . $returnValue))
    {
        $returnValue = $fileName . '-copy-'. $copy . $fileExtension;
        $copy++;
    }
    return $returnValue;
}
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "Sucessfully Uploaded - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

我只是不知道在哪里插上它。我是一个菜鸟所以请放轻松我,请具体。我认为可能有用的选项取自其他问题,但它们对我不起作用,很可能我做错了所以请不要将其标记为“已经问过”谢谢。很抱歉打扰了。

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "<a href='../pie.html' style='border: 5px solid #3a57af;padding-right:50px;padding-bottom:25px;padding-left:50px;display:inline;font-weight:bold;color:#3a57af';> CLICK HERE TO REGISTER</a>";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
html {
   padding-top: 5em;
   font-family: trebuchet, sans-serif;
   font-size: 24px;
   font-weight: bold;
   -webkit-font-smoothing: antialiased;
   text-align: center;
   background: white;
}

body { 
  	padding:0;
  	margin:0;
	text-align:center;
}
div.imageupload {
	padding: 5em 5em 5em 5em;
	height:100vh;
	width:100vh;
	text-align:justify
}
<html>
<head>
<title>Image Submission</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="assets/css/image.css">
<style type="text/css"></style>
</head>
<body>
<div class="imageupload">
<p><h1>Step 1</h1><br>
Please submit a recent photograph to be featured on the homepage of this website.<br><br>
We will place your yearbook picture in the lower right hand corner of the image you submit.<br>
<br>This will allow our classmates to see how we look now and how we looked then.<br><br>
Please select an appropriate image for a website of this nature. <br><br>
The image should show you from your head to at least your knees. <br><br>
The image should not be a group picture, please be the only one in the picture.<br><br> 
Any pictures that do not meet this criteria will be sent back and will not be posted.<br></p>
<form action="PHPmailer/upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form></div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

代替您的$target_file定义,插入重复数据删除功能:

$target_file = renameDuplicates($target_dir, basename($_FILES["fileToUpload"]["name"]));

(我没有检查功能是否正常,但乍一看它应该没问题。)

编辑:功能有点破碎。

function renameDuplicates($path, $file) {   
    $fileName = pathinfo($path . $file, PATHINFO_FILENAME);
    $fileExtension = "." . pathinfo($path . $file, PATHINFO_EXTENSION);

    $returnValue = $path . $fileName . $fileExtension;

    $copy = 1;
    while(file_exists($returnValue))
    {
        $returnValue = $path . $fileName . '-copy-'. $copy . $fileExtension;
        $copy++;
    }
    return $returnValue;
}

检查包含$returnValue的行是否有更改。

答案 1 :(得分:0)

我来救你,并为你写了整篇文章:)

您需要具备以下结构:

upload.php
ImageUpload/uploadMe.php
upload.php中的

<html>
<head>
    <title>Upload Your image here | SiteName</title>
    <!-- Latest compiled and minified Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="row">
            <?php
            $FLAG = $_GET['e'];

            if($FLAG == "UPLOAD_FAILED"){ ?>
            <div class="col-md-12 alert alert-warning">
                Ooops! It looks like an error occured when uploading your image.
            </div>
            <?php } else if($FLAG == "NOT_IMAGE"){ ?>
            <div class="col-md-12 alert alert-warning">
                Hey! Thats not an image?<br/>
                <pre>We only allow: png, jpg, gif and jpeg images.</pre>
            </div>
            <?php } else{} ?> 
            <div class="well col-md-6">
                <form action="ImageUpload/uploadMe.php" method="POST" enctype="multipart/form-data">
                    <legend>
                        Image Upload
                    </legend>

                    <input type="file" name="file" class="form-control btn btn-info"/>
                    <br/>
                    <input type="submit" value="Upload" class="btn btn-primary"/>
                </form>
            </div>
            <div class="well col-md-6">
                <p><h1>Step 1</h1><br>
Please submit a recent photograph to be featured on the homepage of this website.<br><br>
We will place your yearbook picture in the lower right hand corner of the image you submit.<br>
<br>This will allow our classmates to see how we look now and how we looked then.<br><br>
Please select an appropriate image for a website of this nature. <br><br>
The image should show you from your head to at least your knees. <br><br>
The image should not be a group picture, please be the only one in the picture.<br><br> 
Any pictures that do not meet this criteria will be sent back and will not be posted.<br></p>  
            </div>
        </div>
    </div>
</body>
</html>

在ImageUpload / uploadMe.php中:

<?php

if(isset($_FILES['file'])){

$File = $_FILES['file'];


//File properties:
$FileName = $File['name'];
$TmpLocation = $File['tmp_name'];
$FileSize = $File['size'];
$FileError = $File['error'];


//Figure out what kind of file this is:
$FileExt = explode('.', $FileName);
$FileExt = strtolower(end($FileExt));


//Allowed files:
$Allowed = array('jpg', 'png', 'gif', 'jpeg');

//Check if file is allowed:
if(in_array($FileExt, $Allowed)){

    //Does it return an error ?
    //No:
    if($FileError==0){

        $ImageFolder = "uploads";

        //Check if exist, otherwise create it!
        if (!is_dir($ImageFolder)) {
        mkdir($ImageFolder, 0777, true); 
        }
        else{}


        //Create new filename:
        $NewName = uniqid('', true) . rand(123456789,987654321). '.' . $FileExt;
        $UploadDestination = $ImageFolder ."/". $NewName; 

        //Move file to location:
        if(move_uploaded_file($TmpLocation, $UploadDestination)){

            //Yay! Image was uploaded!
            //Do whatever you want here!
        }

        //File didnt upload:
        else{
            //Redirect:
            header("Location: /upload.php?e=UPLOAD_FAILED");
        }
    }

    //An error occured ?
    else{
        //Redirect:
        header("Location: /upload.php?e=UPLOAD_FAILED");
    }

}
//Filetype not allowed!
else{

    //redirect:
    header("Location: /upload.php?e=NOT_IMAGE");
}



}
else{
//No file was submitted :s send them back, eh ?
header("Location: /upload.php");
}

好的,我认为现在已经完成了! 如果您想使用自己的“外观”,只需复制并粘贴<form></form>内容,也许是简单的“错误”处理程序?

有一个好的:)

答案 2 :(得分:0)

 <input class="uploadGAConnection" #uploadFile  type="file" (change)="uploadGAConnectionDetails($event)" placeholder="Upload file" accept=".csv,.json" (click)="uploadFile.value=null">

您只需提供参考并将每次点击的值设置为null。