laravel - Laravel 5 | File upload - If file exists add number to filename
问题描述
I have problem with file upload. Now I have something like this (part of Controller):
if($request->has('photos')) {
foreach ($request->photos as $photo) {
$filename = $photo->getClientOriginalName();
$tmp_name = $filename;
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$uniq_no = 0;
while (file_exists($filename)) {
$tmp_name = $name .'_'. $uniq_no . $ext;
$uniq_no++;
}
$photo->storeAs('public/photos/',$tmp_name);
Photo::create([
'page_id' => $page->id,
'filename' => $tmp_name
]);
}
}
but saves to the database without adding a unique number: filename_0, filename_1 etc. It just saves the value of $tmp_name.
What am I doing wrong?
解决方案
我做了这样的事情:
if($request->has('photos')) {
foreach ($request->photos as $photo) {
$file = $photo->getClientOriginalName();
$filename = pathinfo($file, PATHINFO_FILENAME).'_'.Str::random(6);
$extension = pathinfo($file, PATHINFO_EXTENSION);
$fullfilename = $filename .'.'. $extension;
$photo->storeAs('public/photos/',$fullfilename);
Photo::create([
'page_id' => $page->id,
'filename' => $fullfilename
]);
}
}
推荐阅读
- c++ - 在 Qt C++ 单元测试中动态加载 QQuickWindow 而不是 QQuickWidget
- javascript - 如何应用于许多元素:JavaScript 仅当父元素在视口中时才会对元素产生滚动效果
- machine-learning - KNN 的文本数据降维
- reactjs - 使预填充的文本输入可编辑
- angular - 有没有办法在 Angular/Electron 应用程序中创建无模式对话框?
- python - 有没有办法有条件地设置 seaborn 中的 y 比例?
- python - 函数 DSR 错误 - https://github.com/esvhd/pypbo
- r - any() 函数检查两个 TRUE 而不是一个
- html - Web 应用程序中的 Google Speech to text API
- c++ - 请求 C++ 中嵌入式 for 循环的帮助