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条)

报告相同问题?

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境