php - 使用laravel php循环将变量添加到数据库
问题描述
出于某种原因,我的脚本返回 noimage.jpg 并且没有存储图像。不太清楚为什么?它构造了正确的文件名,但由于某种原因似乎与这两个术语不匹配?例如,它构造了“image1”,但是当“image1”字段被填写时,看不到它们匹配吗?
用户上传照片:
<div class="section4 ">
<div class="row">
<div class="col-lg-3">
<div class="form-group">
{{Form::file('image1.jpg')}}
</div>
<div class="form-group">
{{Form::file('image2')}}
</div>
<div class="form-group">
{{Form::file('image3')}}
</div>
<div class="form-group">
{{Form::file('image4')}}
</div>
</div>
</div>
</div>
控制器:
for($i=1; $i<=16; $i++){
$filenamestr = (string)('image'.$i);
if($request->hasFile($filenamestr)){
// Get filename with the extension
$filenameWithExt = $request->file('image'.$i)->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('image'.$i)->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('image'.$i)->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
}
解决方案
的最终值$fileNameToStore
被设置为循环的第 16 次迭代,即noimage.jpg
. 但是,如果您的图像存在,它看起来仍然应该被存储。
您可以通过创建要存储的文件名数组来解决第一个问题:
for($i=1; $i<=16; $i++){
$filenamestr = (string)('image'.$i);
if($request->hasFile($filenamestr)){
// Get filename with the extension
$filenameWithExt = $request->file('image'.$i)->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('image'.$i)->getClientOriginalExtension();
// Filename to store
$fileNameToStore[$i]= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('image'.$i)->storeAs('public/cover_images', $fileNameToStore[$i]);
} else {
$fileNameToStore[$i] = 'noimage.jpg';
}
}
dd($fileNameToStore);
对于第二个问题,请记住检查您的表单是否已<form enctype="multipart/form-data"...
设置。cover_images
还要检查服务器对您的文件夹有写访问权。
还要检查您的第一个输入的名称,因为它最后不应该有.jpg
。
最后,考虑使用$request->file('image'.$i)->isValid()
before storage 来检查文件是否有效。
最后
考虑使用数组输入而不是编号字段。即调用每个字段{{Form::file('image[]')}}
并使用 Laravel 对dot
符号的支持或foreach($request)->file()
推荐阅读
- python-3.x - 数据流作业卡在从 Pub/Sub 读取
- python - 如何在熊猫中通过交换列名过滤重复项
- google-api - 如何使用谷歌云 API 启用 Dialogflow API
- python - Django 项目中的 MultiValueDictKeyError
- node.js - Node.js - 监听系统进程
- c# - 如何使用正则表达式查找添加的门牌号码(在地址中)
- php - 使用带有 CURL PHP 的 REST api 删除 Azure blob
- microservices - 两个微服务之间的事务
- c# - 检查所有路由是否已验证 netcore 3.1
- javascript - 格式化输入电话号码,不能删除插入的数据