在Laravel 4中上传多个文件
这是我用于上传多个文件的控制器代码,我正在从Google Chrome上的邮递员" rest API客户端传递密钥和值.我正在从邮递员添加多个文件,但只有1个文件正在上传.
Here is my controller code for uploading multiple files and I am passing key and value from 'postman' rest API client on Google Chrome. I am adding multiple files from postman but only 1 file is getting upload.
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);
}
}
}
}
}
我也尝试过此代码,但它会向我返回临时文件夹中文件的位置
I have tried this code also but it returns me location of a file in temporary folder
$file = Input::file('file');
echo count($file);
和
echo count($_FILES['file']);
总是让我返回5.有人可以告诉我为什么吗?
and
echo count($_FILES['file']);
returns me always 5.Can anyone tell me why?
以及为什么foreach(Input::file('file') as $key => $abc)
给出错误的无效参数
and why foreach(Input::file('file') as $key => $abc)
gives the error invalid arguments
不使用任何API,但这可能会概述该原理.
Not using any API, but this might outline the principle.
我设置了这个route.php文件,whick将帮助您进行上传测试.
I set up this routes.php file, whick will help you with upload test.
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();
});
请注意输入名称files []::如果要上传相同名称的多个文件,请同时加上方括号.
Notice the input name, files[]: If uploading multiple files under the same name, include brackets as well.