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条)

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行