问题描述
我有一个包含三个输入字段的表单.我想在处理输入值之前先对其进行验证.我要在处理文件之前验证文件名的位置.我使用正则表达式和alpha_dash.但是我得到了一个错误的有效文件名.我只希望文件名包含小写字母,数字,下划线和破折号.如何检查文件名的有效性?
I have a form with three input fields. I want to validate the input value before processing them. Where I want to validate the file name before processing it. I use regular expression and alpha_dash. But I got an error for a valid file name. I want my file name only to contain small letter, numbers, underscore and dashes. How can I check the validation of the file name for my file?
HTML
<form action="create" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<table cellpadding="2" width="20%" align="center"
cellspacing="2">
<tr>
<td colspan=2>
<center><font size=4><b>Add the iteams please</b></font></center>
</td>
</tr>
<tr>
<td>Heading</td>
<td><input type="text" name="heading" id="heading" size="30">
{!! $errors->first('heading', '<p class="red">:message</p>') !!}
</td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" name="image" id="image" size="40">
{!! $errors->first('image', '<p class="red">:message</p>') !!}
</td>
</tr>
<tr>
<td></td>
<td colspan="2"><input type="submit" name="submit" value="Add Item" /></td>
</tr>
</table>
</form>
控制器部分
- 使用正则表达式格式:
-我收到错误消息,图像格式无效".
public function store(){
$this->validate(request(),[
'heading'=>'required',
'contentbody'=>'required',
‘image'=>['required','image','mimes:jpeg,png,jpg,gif,svg','max:2048','regex:/^[a-z0-9-_]+$/' ]
]);
}
- 使用Alpa_dash:
-我收到错误消息,图像只能包含字母,数字和破折号".
public function store(){
$this->validate(request(),[
'heading'=>'required',
'contentbody'=>'required',
'image'=>'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|alpha_dash'
}
请帮助,谢谢!
推荐答案
如果其他人也遇到与我相同的问题.我通过将文件名更改为当前时间戳而不是使用原始文件名来解决了我的问题.这样,我不必担心要保存在数据库中的原始文件名的验证.
If somebody else has the same problem like me. I solved my problem by changing the filename to the current time-stamp instead of using the original filename. That way, I don't need to be worried about the validation of the original filename to be saved in the database.
public function store(Request $request)
{
$this->validate($request,[
'heading'=>'required',
'contentbody'=>'required',
'image'=>['required','image','mimes:jpg,png,jpeg,gif,svg','max:2048']
]);
if($request->hasFile('image')){
$inputimagename= time().'.'.$request->file('image')->getClientOriginalExtension();
$request->image->storeAs('public/upload', $inputimagename);
Post::create([
'heading'=>request('heading'),
'content'=>request('contentbody'),
'image'=>$inputimagename,
]);
}
return redirect('/home');
}
这篇关于如何在Laravel 5.4中验证文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!