【问题标题】:Accept uploaded files with the same name?接受上传的同名文件?
【发布时间】:2015-12-30 04:20:16
【问题描述】:

我有一个表单,人们可以在其中上传单个图像。大多数人都从他们的移动设备上传图片。每个拥有 iPhone 的人都将他们的图像上传为“image.png”。我需要让我的表单不拒绝它,而只接受具有相同名称的文件而不删除旧文件或将它们重命名为“imageupload1.png”、“imageupload2.png”甚至 image.png 然后“image-Copy.png”。 png”然后是“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>

【问题讨论】:

  • 通常您只需为上传的文件创建一个临时名称。但是,如果您不知道自己在做什么,那么使用允许访问者上传文件的脚本可能会带来巨大的安全风险。看看我在this question 中的回答。它处理大多数安全问题以及唯一名称,但仍然能够将原始文件名返回给访问图像/视频等的任何人。
  • @icecub 好的,很酷,谢谢,我会检查一下。文件上传的目的是让我的老同学上传一张他们自己的照片,以便在我们的十年重聚网站上展示。所以原始文件名并不重要,因为我将图像单独放在其他地方。不过谢谢。

标签: php html css forms file-upload


【解决方案1】:

插入您的 dedup 函数,而不是您的 $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 的行是否有更改。

【讨论】:

  • 我要试试这个。谢谢
  • 那么函数有错误,我想。哪个致命错误,在哪一行?
  • 第 3 行我更改了 "$target_file = $target_dir .basename($_FILES["fileToUpload"]["name"]);" to "$target_file = renameDuplicates($target_dir, basename($_FILES["fileToUpload"]["name"]));"
  • 这不是我的问题。 PHP 报告了哪个错误?它是在哪一行报告的?
  • 致命错误:在第 3 行的 /../../../../../uploads.php 中调用未定义函数 renameDuplicates()
【解决方案2】:

我来救你了,为你写了整件事:)

你需要有这样的结构:

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");
}

好的,我想它现在完成了! 如果您想使用自己的“查看”,只需复制并粘贴 &lt;form&gt;&lt;/form&gt; 内容,也许还可以使用简单的“错误”处理程序?

祝你好运:)

【讨论】:

    【解决方案3】:
     <input class="uploadGAConnection" #uploadFile  type="file" (change)="uploadGAConnectionDetails($event)" placeholder="Upload file" accept=".csv,.json" (click)="uploadFile.value=null">
    

    您可以简单地给出一个引用,并在每次点击时将其值设置为 null。

    【讨论】:

      猜你喜欢
      • 2023-01-30
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 2012-10-02
      • 2015-07-31
      • 2014-02-24
      • 2012-05-12
      • 1970-01-01
      相关资源
      最近更新 更多