从html表单上传后重命名文件


renaming file after upload from html form

这是上传表单

<html>
    <body>
        <form action="upload.php" method="post" enctype="multipart/form-data">
            <label for="file">Filename:</label>
            <input type="file" name="uploaded" id="file"><br>
            <input type="submit" name="submit" value="Submit">
        </form>
    </body>
</html>

这就是php:

<?php
    $keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for ($i = 0; $i < 10; $i++) { 
        $photoID .= $keys[rand(0, strlen($keys)-1)];
    } 
    //add a dot (.) to the randomly generated string so the ext can be applied to it later
    $photoID2 = $photoID.".jpg";
    //This assigns the subdirectory you want to save into... make sure it exists!
    $target = "uploads/";
    //This combines the directory, the random file name, and the extension
    $target = $target . $photoID2.$ext; 
    if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) {
        echo "The file has been uploaded as ".$photoID2.$ext;
    } else {
        echo "Error: upload did not work";
    }
?>

我的问题是,我一直得到错误上传不起作用。。。我在这里做错了什么?这真的是我缺少的基本东西,但我需要理解它,因为我已经可以很好地上传文件了,但我想了解它是如何工作的。。。

第一个:
确保有一个名为uploads
的目录第二个:
尝试使用类似chmod的向目录授予适当的权限

chmod -R 777 /path/to/the/directory

使用以下代码重命名上传的文件

$name = $_FILES['Fixtures']['uploaded']['name'];
$tmp_name = $_FILES['uploaded']['tmp_name'];
$target_path = "images/uploads/";
$extension = end(explode('.', $name));
$randomName = 'thumbnail_' . rand(123456, 1234567890) . '.' . $extension;
/* Add the original filename to our target path.  
  Result is "images/uploads/filename.extension" */
$target_path = $target_path . basename($randomName);
$allowedImageTypes = array("image/jpeg", "image/jpg", "image/png", "image/x-png", "image/gif");
if (in_array($type, $allowedImageTypes)) {
    move_uploaded_file($tmp_name, $target_path) or die("error in thumbnail upload!");
}

这将上传所有文件,并重命名文件

检查上传的文件夹权限/是否可为apache写入。

并尝试设置错误报告,以便move_uploaded_file可以告诉您出了什么问题。

我想我会接受这个解决方案,它对我来说更有意义,move_uploaded_files是把它放在目录中并给它命名的。

<?php 
  //create random file name
    $keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
     for ($i = 0; $i < 7; $i++)    
        {                         
      $key .=  $keys[rand(0, strlen($keys)-1)];      
      }
 //get the extension
  $ext = basename( $_FILES['uploaded']['type']);
 //choose destination, add filename and extension
   $target = "uploads/" .$key. "." . $ext; 

 //move the file to the des
   if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
 {
  echo "The file has been uploaded";
  } 
  else {
 echo "Sorry, there was a problem uploading your file.";
 }
  ?>