2015-10-26 3 views
0

В настоящее время у меня есть форма с 2x name=userfile[] атрибутами на входах, которые обрабатываются в коде ниже. Что бы лучший способ, чтобы я мог переименовать файл имена файлов Еогеасп при загрузке - Я хочу, чтобы они были специфичны для 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 

    } 
    } 
} 
+0

Вы можете добавить случайный сгенерированный ключ с каждым файлом. –

+0

'лучший способ разрешить мне переименовать имена файлов' почему? Я имею в виду, какова проблема, с которой вы сталкиваетесь сейчас? – Jigar

+0

Несколько подробностей с изображениями diff, и я просто суетливый, и я хочу, чтобы все было в порядке, я знаю, что, если какой-либо из кодовых разрывов –

ответ

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> 

Php

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 

      } 
     } 
    } 
} 
} 
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; 
+0

Могу ли я установить имя файла для каждой загрузки? –

+0

да попробуйте мой код @JessMcKenzie –

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 
Смежные вопросы