我在下面的代码中遇到了一些错误,我搜索了很多但是我没有得到解决方案。我想上传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.
答案 0 :(得分:2)
你应该将此attr添加到表单元素:
enctype="multipart/form-data"
答案 1 :(得分:1)
我也通过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
}
您仍然可以保留文件大小的规则
答案 2 :(得分:1)
Laravel 6:
我尝试上传扩展名为webm
的视频。
dd($request)
返回mimetype:video/webm
,我试图在规则中使用它。但是我得到了mimetype错误错误。
我检查了另一个$request->file('video')->getMimeType()
,并得到了video/x-matroska
。我使用规则mimetypes:video/x-matroska
。它对我有用。
答案 3 :(得分:0)
我试过,我找到了解决方案。
// 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);
}