ric*_*cha 8 php upload file laravel
这是我用于上传多个文件的控制器代码,我从Google Chrome上的'postman'rest API客户端传递密钥和值.我正在从邮递员添加多个文件,但只有1个文件正在上传.
public function post_files() {
$allowedExts = array("gif", "jpeg", "jpg", "png","txt","pdf","doc","rtf","docx","xls","xlsx");
foreach($_FILES['file'] as $key => $abc) {
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$filename= $temp[0];
$destinationPath = 'upload/'.$filename.'.'.$extension;
if(in_array($extension, $allowedExts)&&($_FILES["file"]["size"] < 20000000)) {
if($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
if (file_exists($destinationPath)) {
echo $filename." already exists. ";
} else {
$uploadSuccess=move_uploaded_file($_FILES["file"]["tmp_name"],$destinationPath);
if( $uploadSuccess ) {
$document_details=Response::json(Author::insert_document_details_Call($filename,$destinationPath));
return $document_details; // or do a redirect with some message that file was uploaded
// return Redirect::to('authors')
} else {
return Response::json('error', 400);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我也试过这个代码,但它返回我在临时文件夹中的文件的位置
$file = Input::file('file');
echo count($file);
Run Code Online (Sandbox Code Playgroud)
并且
echo count($_FILES['file']);
总是给我回报5.任何人都可以告诉我为什么?
以及为什么foreach(Input::file('file') as $key => $abc)
给出错误无效的参数
And*_*yco 22
不使用任何API,但这可能概述了原则.
我设置了这个routes.php文件,whick将帮助你进行上传测试.
routes.php文件
// save files
Route::post('upload', function(){
$files = Input::file('files');
foreach($files as $file) {
// public/uploads
$file->move('uploads/');
}
});
// Show form
Route::get('/', function()
{
echo Form::open(array('url' => 'upload', 'files'=>true));
echo Form::file('files[]', array('multiple'=>true));
echo Form::submit();
echo Form::close();
});
Run Code Online (Sandbox Code Playgroud)
注意输入名称files []:如果以相同的名称上传多个文件,也包括括号.
fid*_*per 21
您只需执行以下操作即可获取所有文件:
$allFiles = Input::file();
Run Code Online (Sandbox Code Playgroud)
这堂课Input
实际上是班级的门面Illuminate\Http\Request
(是的,就像Request
门面一样 - 它们都是同一个班级的"面孔"!**).
这意味着您可以使用Request中的任何可用方法.
如果我们搜索该函数file()
,我们看到它的工作原理如下:
public function file($key = null, $default = null)
{
return $this->retrieveItem('files', $key, $default);
}
Run Code Online (Sandbox Code Playgroud)
现在,retrieveItem()
是一个受保护的方法,所以我们不能直接从我们的Controller中调用它.然而,仔细观察,我们发现我们可以file()
为密钥传递方法"null".如果我们这样做,那么我们将获得所有物品!
protected function retrieveItem($source, $key, $default)
{
if (is_null($key))
{
return $this->$source->all();
}
else
{
return $this->$source->get($key, $default, true);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我们调用Input::file()
,Request类将在内部运行$this->retrieveItem('files', null, null)
,而后者将依次运行return $this->files->all();
,我们将获取所有上传的文件.
**请注意,Input
Facade中有额外的get()方法.