我在以下代码中出现一些错误,我进行了很多搜索,但没有得到解决方案。我想上传file.xls,对吗?谢谢
我的HTML表单:
<form class="form-horizontal" role="form" method="post" action="{{ URL::to('doc/test') }}" enctype="multipart/form-data">
<input style='width:400px;' type='file' id='files' name='files[]' class="form-control" multiple='multiple'>
<button type="submit" class="btn btn-primary">Save</button>
</form>
我的控制器功能
public function uploadDocs()
{
$files = Input::file('files');
$errors = "";
foreach($files as $file)
{
$rules = array('file' => 'mimes:png,gif,jpeg,pdf,doc,docx,xls,xlsx,max:1000000'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
$destinationPath = 'documents';
$filename = $file->getClientOriginalName();
$temp = explode(".", $filename);
$extension = end($temp);
$filename = $temp[0].'_'.date('Y-m-d H:i:s').$extension;
$upload_success = $file->move($destinationPath, $filename);
}
else
{
return Redirect::back()->withErrors($validator);
}
}
}
错误:
The file must be a file of type: png, gif, jpeg, pdf, doc, docx, xls, xlsx, max:1000000.
您应该将此attr添加到表单元素:
enctype="multipart/form-data"
我也通过laravel的验证器进行mime类型验证时遇到了问题,所以我最终使用类似的方法手动完成了该任务
$supported_mime_types = array('application/vnd.ms-excel');
$file = Input::file('file');
$mime = $file->getMimeType();
if (!in_array($mime, $supported_mime_types)) {
// mime type not validated
}
您仍然可以保留文件大小的规则
Laravel 6:
我尝试上传扩展名为webm
的视频。
[dd($request)
返回mimetype:video/webm
,分别,我尝试在规则中使用它。但是我得到了mimetype错误错误。
我检查了另一个$request->file('video')->getMimeType()
并得到了video/x-matroska
。而且我使用了规则mimetypes:video/x-matroska
。它对我有用。
我尝试过,找到了解决方案。
// validating each file.
$rules = array('file' => 'required');
$validator = Validator::make(
[
'file' => $file,
'extension' => \Str::lower($file->getClientOriginalExtension()),
],
[
'file' => 'required|max:100000',
'extension' => 'required|in:jpg,jpeg,bmp,png,doc,docx,zip,rar,pdf,rtf,xlsx,xls,txt'
]
);
if($validator->passes())
{
// path is root/uploads
$destinationPath = 'documents';
$filename = $file->getClientOriginalName();
$temp = explode(".", $filename);
$extension = end($temp);
$filename = $temp[0].'_'.date('Y-m-d H:i:s').'.'.$extension;
$upload_success = $file->move($destinationPath, $filename);
if( $upload_success)
{
return Response::json('success', 200);
}
else
{
$errors .= json('error', 400);
}
}
else
{
// redirect back with errors.
return Redirect::back()->withErrors($validator);
}