2015-09-15 57 views
3

我有一小段代码将从窗体中获取请求输入文件并将它移动到一个文件夹中。那就是:在一个文件夹中存储图像laravel

$destinationPath = 'uploads'; 

$filename = $file->getClientOriginalName(); 

$upload_success = $file->move($destinationPath, $filename); 

是,上面的代码工作,但那么我想要做的是,在每次我上传图片,就会有一个唯一的名称,这样就不会覆盖该文件夹中的任何图片。现在这就是我所做的:像7c724458520a11c68747793c86554127_Jellyfish.jpg

function generateRandomString($length = 8) { 
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
    $charactersLength = strlen($characters); 
    $randomString = ''; 
    for ($i = 0; $i < $length; $i++) { 
     $randomString .= $characters[rand(0, $charactersLength - 1)]; 
    } 
    return $randomString; 
} 

$destinationPath = 'uploads'; 
$rand = md5(generateRandomString()); 
$filename = $rand."_".$file->getClientOriginalName(); 
$upload_success = $file->move($destinationPath, $filename); 

这将输出的东西,但它看起来凌乱。这有什么窍门吗?谢谢。

+2

删除'md5';' –

+1

为什么不检查文件是否存在,如果它是否将_1添加到新的文件名? – Epodax

+0

是@Abdulla是对的。因为你生成一个随机字符串,然后散列它。 – aldrin27

回答

2

只是在这里删除md5$rand = md5(generateRandomString());

因为你生成一个随机字符串,然后散列它

+0

您可能想检查我的答案并提出更多建议。谢谢。 – FewFlyBy

1

我我设法解决了我的问题。首先由Abdulla的建议,然后通过这样除去md5:在这里`$兰特= MD5(generateRandomString())

$destinationPath = 'uploads'; 
$rand = generateRandomString(); 

$file_list = File::files('uploads'); //returns an array of all of the files in a given directory. 

do { 
    $filename = $rand."_".$file->getClientOriginalName(); 
} while(in_array("uploads/".$filename, $file_list)); //keep generating a string until it doesn't exist in the given directory. 

$upload_success = $file->move($destinationPath, $filename); //move the file 
相关问题