douxu9707 2015-09-15 07:05
浏览 77
已采纳

将图像存储在文件夹laravel中

I have a small piece of code that will get the request input file from the form and will move it to a folder. Here it is:

$destinationPath = 'uploads';

$filename = $file->getClientOriginalName();

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

Yes, the code above works but then what I wanted to do is each time I upload an image, it will have a unique name so it wouldn't overwrite any picture in the folder. For now this is what I did:

function generateRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $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);

This will output something like 7c724458520a11c68747793c86554127_Jellyfish.jpg but it looks untidy. Is there a trick for this? Thank you.

  • 写回答

3条回答 默认 最新

  • douyinzha5820 2015-09-15 07:11
    关注

    just remove md5 on here $rand = md5(generateRandomString());

    Because you generate a random string then hashed it

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题