dtlab08822 2018-04-04 12:24
浏览 77
已采纳

PHP使用随机名称上传多个文件

I got problem to set file name when uploading the image using multiple input file.

<span class="btn btn-default btn-file">
    Browse <input type="file" name="image[]" id="image" class="image" onchange="preview_image();" multiple/>
</span>

And here is the PHP:

$total = count($_FILES['image']['name']);

for($i=0; $i<$total; $i++)
{
    $tmpFilePath = $_FILES['image']['tmp_name'][$i];

    if($tmpFilePath != "")
    {
        $info1 = pathinfo($_FILES['image']['name'][$i]);
        $ext = $info1['extension'];
        $newname1 = "CALIBRATION_.".$ext; 

        $newFilePath = "../assets/img/product/" . $newname1[$i];

        if(move_uploaded_file($tmpFilePath, $newFilePath)){}
    }
}

When I try to run the code, it show me wrong name & type. You can see below screenshot.

enter image description here

What I want is to rename the file after uploaded with correct name and file type.

  • 写回答

4条回答 默认 最新

  • douliandan7340 2018-04-04 12:28
    关注

    You access $newname1 as an array, this is not what you want. Plus, you are missing the random of your name.

    try doing

    $total = count($_FILES['image']['name']);
    
    for($i=0; $i<$total; $i++)
    {
        $tmpFilePath = $_FILES['image']['tmp_name'][$i];
    
        if($tmpFilePath != "")
        {
            $info1 = pathinfo($_FILES['image']['name'][$i]);
            $ext = $info1['extension'];
            $newname1 = "CALIBRATION_" . rand(10000,99999) . "." . $ext; 
    
            $newFilePath = "../assets/img/product/" . $newname1;
    
            if(move_uploaded_file($tmpFilePath, $newFilePath)){}
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?