1

Laravel 4でアップロードされたファイルの名前を変更するにはどうすればよいですか。これまでのところ、私は次のようにしています:

$file = Input::file('file'); 
$destinationPath = 'public/downloads/';
if (!file_exists($destinationPath)) {
    mkdir("./".$destinationPath, 0777, true);
}
$filename = $file->getClientOriginalName();

ただ、同じ名前のファイルが2つあると書き換えられてしまうのではないかと思うので(2)、2番目のファイル名の末尾に何かを追加したり、ファイル名を完全に変更したりしたいと考えています

4

2 に答える 2

3

最初のステップは、ファイルが存在するかどうかを確認することです。そうでない場合は、ファイル名と拡張子を抽出pathinfo()し、次のコードで名前を変更します。

$img_name = strtolower(pathinfo($image_name, PATHINFO_FILENAME));
$img_ext =  strtolower(pathinfo($image_name, PATHINFO_EXTENSION));

$filecounter = 1; 

while (file_exists($destinationPath)) {
    $img_duplicate = $img_name . '_' . ++$filecounter . '.'. $img_ext;
    $destinationPath = $destinationPath . $img_duplicate;  
}

ループは、条件が true を返す限りfile_1、ファイルの名前を などに変更し続けます。file_2file_exists($destinationPath)

于 2013-06-24T18:47:48.893 に答える