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

时间:2013-12-02 10:10:29

标签: php html

这是上传表单

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

我遇到的问题是我不断上传错误上传不起作用......我在这里做错了什么?这是我缺少的基本内容,但我需要了解它,因为我已经可以完成文件上传,但想了解它是如何工作的......

4 个答案:

答案 0 :(得分:1)

<强>首先
 确保有一个名为uploads的目录 的第二
尝试使用chmod(如

)为目录提供合适的权限
chmod -R 777 /path/to/the/directory

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

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

并尝试设置error reporting,以便move_uploaded_file可以告诉您哪里出错了。

答案 3 :(得分:0)

我想我会解决这个问题,对我来说更有意义,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.";
 }
  ?>