上传时更改文件名

时间:2015-10-26 05:11:40

标签: php

我目前在输入中有一个包含2x name=userfile[]属性的表单,在下面的代码中处理。什么是让我在上传时重命名文件名foreach文件的最佳方法 - 我希望它们特定于input

我的目标:

$imageOneName = img1.$var;
$imageTwoName = img2.$var;

代码:

for($i=0; $i<count($_FILES['userfile']['name']); $i++) {
  //Get the temp file path
  $tmpFilePath = $_FILES['userfile']['tmp_name'][$i];

  //Make sure we have a filepath
  if ($tmpFilePath != ""){
    //Setup our new file path
    $newFilePath = $local_path .'images/' . $_FILES['userfile']['name'][$i];


    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {

      //Handle other code here

    }
  }
}

3 个答案:

答案 0 :(得分:1)

试试这段代码: -

$extension = pathinfo($_FILES['userfile']['name'][$i], PATHINFO_EXTENSION); //Get extension of image
$new= rand(0000,9999); //creat random name
$file_name=$new.'.'.$extension; //create file name with extension
$newFilePath = $local_path .'images/' . $file_name;

答案 1 :(得分:1)

使用以下代码为每个文件生成唯一的文件名。

$file_name = preg_replace('/\s+/', '', $_FILES['userfile']['name'][$i]); /// remove unexpected symbols , number 
$path[$i]="image/".time().$i.$file_name; /// generate unique name
move_uploaded_file($file_tmp[$i],$path[$i]); /// move that file on your path folder

答案 2 :(得分:1)

而不是

<input type="file" name="userfile[]" id="input1">
<input type="file" name="userfile[]" id="input2">

您可以执行以下操作来区分两者

<input type="file" name="userfile[desiredNameOfFile1]" id="input1">
<input type="file" name="userfile[desiredNameOfFile2]" id="input2">

使用PHP处理它:

foreach($_FILES['userFile']['name'] AS $desiredNameOfFile => $fileInfo) {
  //Get the temp file path
  $tmpFilePath = $_FILES['userfile']['tmp_name'][$desiredNameOfFile];

  //Make sure we have a filepath
  if ($tmpFilePath != ""){
    //Setup our new file path
    $newFilePath = $local_path .'images/' . $desiredNameOfFile . pathInfo($_FILES['userfile']['tmp_name'][$desiredNameOfFile],PATHINFO_EXTENSION);


    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {

      //Handle other code here

    }
  }
}

请注意:此代码将覆盖已具有该名称的文件

修改

如果您想要多个文件选择

<input type="file" name="userfile[desiredNameOfFile1][]" id="input1" multiple>
<input type="file" name="userfile[desiredNameOfFile2][]" id="input2" multiple>

foreach($_FILES['userfile']['name'] AS $desiredNameOfFile => $fileInfo) {
    for($i = 0; $i < count($fileInfo); $i++) {
    //Get the temp file path
        $tmpFilePath = $_FILES['userfile']['tmp_name'][$desiredNameOfFile][$i];

        // Make sure we have a filepath
        if ($tmpFilePath != ""){
            // Setup our new file path
            $newFilePath = $local_path .'images/' . $desiredNameOfFile . $i . pathInfo($_FILES['userfile']['tmp_name'][$desiredNameOfFile][$i],PATHINFO_EXTENSION);


            // Upload the file into the temp dir
            if(move_uploaded_file($tmpFilePath, $newFilePath)) {

                // Handle other code here

            }
        }
    }
}
}