如何上传&使用所需名称保存文件

时间:2010-08-18 05:57:05

标签: php file-upload

我正在使用此代码上传文件(图像到文件夹)

<form action='' method='POST' enctype='multipart/form-data'>
<input type='file' name='userFile'><br>
<input type='submit' name='upload_btn' value='upload'>
</form>

<?php
$target_Path = "images/";
$target_Path = $target_Path.basename( $_FILES['userFile']['name'] );
move_uploaded_file( $_FILES['userFile']['tmp_name'], $target_Path );
?>

当文件(图像)保存在指定路径时...如果我想保存带有某个所需名称的文件,那该怎么办....

我试过替换这个

$target_Path = $target_Path.basename( $_FILES['userFile']['name'] );

有了这个

$target_Path = $target_Path.basename( "myFile.png" );

但是它无效

9 个答案:

答案 0 :(得分:100)

你可以试试这个,

$info = pathinfo($_FILES['userFile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext; 

$target = 'images/'.$newname;
move_uploaded_file( $_FILES['userFile']['tmp_name'], $target);

答案 1 :(得分:7)

这会很好用 - 您可以使用HTML5仅允许上载图像文件。 这是uploader.htm的代码 -

<html>    
    <head>
        <script>
            function validateForm(){
                var image = document.getElementById("image").value;
                var name = document.getElementById("name").value;
                if (image =='')
                {
                    return false;
                }
                if(name =='')
                {
                    return false;
                } 
                else 
                {
                    return true;
                } 
                return false;
            }
        </script>
    </head>

    <body>
        <form method="post" action="upload.php" enctype="multipart/form-data">
            <input type="text" name="ext" size="30"/>
            <input type="text" name="name" id="name" size="30"/>
            <input type="file" accept="image/*" name="image" id="image" />
            <input type="submit" value='Save' onclick="return validateForm()"/>
        </form>
    </body>
</html>

现在是upload.php的代码 -

<?php  
$name = $_POST['name'];
$ext = $_POST['ext'];
if (isset($_FILES['image']['name']))
{
    $saveto = "$name.$ext";
    move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
    $typeok = TRUE;
    switch($_FILES['image']['type'])
    {
        case "image/gif": $src = imagecreatefromgif($saveto); break;
        case "image/jpeg": // Both regular and progressive jpegs
        case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
        case "image/png": $src = imagecreatefrompng($saveto); break;
        default: $typeok = FALSE; break;
    }
    if ($typeok)
    {
        list($w, $h) = getimagesize($saveto);
        $max = 100;
        $tw = $w;
        $th = $h;
        if ($w > $h && $max < $w)
        {
            $th = $max / $w * $h;
            $tw = $max;
        }
        elseif ($h > $w && $max < $h)
        {
            $tw = $max / $h * $w;
            $th = $max;
        }
        elseif ($max < $w)
        {
            $tw = $th = $max;
        }

        $tmp = imagecreatetruecolor($tw, $th);      
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
        imageconvolution($tmp, array( // Sharpen image
            array(−1, −1, −1),
            array(−1, 16, −1),
            array(−1, −1, −1)      
        ), 8, 0);
        imagejpeg($tmp, $saveto);
        imagedestroy($tmp);
        imagedestroy($src);
    }
}
?>

答案 2 :(得分:1)

您可以从此处获取演示源代码:http://abhinavsingh.com/blog/2008/05/gmail-type-attachment-how-to-make-one/

可以使用,也可以根据应用需求进行修改。 希望它有所帮助:)

答案 3 :(得分:0)

将其用于上传目标路径

<?php
$file_name = $_FILES["csvFile"]["name"];
$target_path = $dir = plugin_dir_path( __FILE__ )."\\upload\\". $file_name;
echo $target_path;
move_uploaded_file($_FILES["csvFile"]["tmp_name"],$target_path. $file_name);
?>

答案 4 :(得分:0)

配置“php.ini”文件

首先,确保将PHP配置为允许文件上载。 在“php.ini”文件中,搜索file_uploads指令,并将其设置为On:

file_uploads = On 

创建HTML表单

接下来,创建一个允许用户选择要上传的图片文件的HTML表单:

<!DOCTYPE html>
<html>
<body>

<form action="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>

</body>
</html>

上面的HTML表单要遵循的一些规则:     确保表单使用method =“post”     表单还需要以下属性:enctype =“multipart / form-data”。它指定在提交表单时使用的内容类型 如果没有上述要求,文件上传将无效。 其他需要注意的事项:     标签的type =“file”属性将输入字段显示为文件选择控件,输入控件旁边有“浏览”按钮 上面的表单将数据发送到名为“upload.php”的文件,我们将在下一步创建该文件。

创建上传文件PHP脚本

“upload.php”文件包含上传文件的代码:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// 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 "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>

答案 5 :(得分:0)

我知道出了什么问题,您发现您在此使用了“”而不是“

$target_Path = $target_Path.basename( 

   "myFile.png"

);

答案 6 :(得分:0)

只需获取文件扩展名,然后使用uniqid为文件分配一个新名称,并将新名称传递给move_upload_file方法。例如:

if(isset($_POST['submit'])){
  $total = count($_FILES['files']['tmp_name']);
  for($i=0;$i<$total;$i++){
    $fileName = $_FILES['files']['name'][$i];
    $ext = pathinfo($fileName, PATHINFO_EXTENSION);
    $newFileName = uniqid();
    $fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
    if($ext === 'pdf' || 'jpeg' || 'JPG'){
        move_uploaded_file($_FILES['files']['tmp_name'][$i], $fileDest);
        $fileUpload = $newFileName.'.'.$ext[$i].',<br>';
    }else{
      echo 'Pdfs and jpegs only please';
    }
  }
}

答案 7 :(得分:0)

 <html>
<head>
<title>PHP Reanme image example</title>
</head>
<body>

<form action="fileupload.php" enctype="multipart/form-data" method="post">
Select image :
<input type="file" name="file"><br/>
Enter image name :<input type="text" name="filename"><br/>
<input type="submit" value="Upload" name="Submit1">

</form>

<?php

if(isset($_POST['Submit1']))
{ 


$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$name = $_POST["filename"];

move_uploaded_file($_FILES["file"]["tmp_name"], $name.".".$extension);
echo "Old Image Name = ". $_FILES["file"]["name"]."<br/>";
echo "New Image Name = " . $name.".".$extension;

}


?>
</body>
</html>

点击[此处](https://meeraacademy.com/php-rename-image-while-image-uploading/

答案 8 :(得分:-2)

以下是PHP中用于上传图像,将其保存到数据库,显示并保存到文件夹的代码。

  1. 首先,表单的HTML代码为:

    <div class="upload">
        <form method="POST" enctype="multipart/form-data" id="imageform">
           <br>
           <input type="file" name="image" id="photoimg" >
           <br><br>
           <input type="submit" name="submit" value="UPLOAD">
       </form>
    </div>
    
  2. PHP代码

  3. 根据需要创建数据库和表。(只需要2个字段) 在表格中,id(INT) 255 primary key AUTO INCREMENT and your image row(anyname) (MEDIUMBLOB)

    <?php
    
    if(isset($_POST['submit'])){
        if(@getimagesize($_FILES['image']['tmp_name']) == FALSE){
            echo "<span class='image_select'>please select an image</span>";
    
        }
        else{
            $image = addslashes($_FILES['image']['tmp_name']);
            $name  = addslashes($_FILES['image']['name']);
            $image = file_get_contents($image);
            $image = base64_encode($image);
            saveimage($name,$image);
            $uploaddir = 'profile/'; //this is your local directory
            $uploadfile = $uploaddir . basename($_FILES['image']['name']);
    
            echo "<p>";
    
                if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {// file uploaded and moved} 
                else { //uploaded but not moved}
    
            echo "</p>";
    
    
    
        }
    
    }
    
    displayimage();
    function saveimage($name,$image)
    {
        $con = mysql_connect("localhost","root","your database password");
        mysql_select_db("your database",$con);
        $qry  = "UPDATE your_table SET your_row_name='$image'";
            $result = @mysql_query($qry,$con);
    
        if($result)
        {
            echo "<span class='uploaded'>IMAGE UPLOADED</span>";
    
        }
        else
        {
            echo "<span class='upload_failed'>IMAGE NOT UPLOADED</span>";
    
        }
    }
    function displayimage()
    {
        $con = mysql_connect("localhost","root","your_password");
        mysql_select_db("your_database",$con);
        $qry  = "select * from your_table";
        $result = mysql_query($qry,$con);
    
        while($row  = mysql_fetch_array($result))
        {
            echo '<img class="image" src="data:image;base64,'.$row[1].'">';
    
        }
    
    
    
        mysql_close($con);
    }
    ?>