这是我用于上传多个文件的 Controller 代码,我从 Google Chrome 上的“postman”rest API 客户端传递 key 和值。我正在从 postman 添加多个文件,但只有 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);
}
}
}
}
}
我也试过这段代码,但它返回临时文件夹中文件的位置
$file = Input::file('file');
echo count($file);
和
回显计数($_FILES['file']);
总是返回我 5.谁能告诉我为什么?
以及为什么 foreach(Input::file('file') as $key => $abc)
给出错误参数无效
最佳答案
解决方案:
您只需执行以下操作即可获取所有文件:
$allFiles = Input::file();
说明:
Input
类实际上是 Illuminate\Http\Request
类的 Facade(是的,就像 Request
facade - 它们都是充当同类的“面子”!**)。
这意味着您可以使用 Request 中可用的任何方法。
如果我们搜索函数 file()
,我们看到它是这样工作的:
public function file($key = null, $default = null)
{
return $this->retrieveItem('files', $key, $default);
}
现在,retrieveItem()
是一个 protected 方法,所以我们不能直接从 Controller 调用它。然而,深入观察,我们看到 we can pass the file()
method "null"为关键。如果我们这样做,那么我们将获得所有元素!
protected function retrieveItem($source, $key, $default)
{
if (is_null($key))
{
return $this->$source->all();
}
else
{
return $this->$source->get($key, $default, true);
}
}
因此,如果我们调用 Input::file()
,Request 类将在内部运行 $this->retrieveItem('files', null, null)
这将依次运行 return $this->files->all();
我们将获得所有上传的文件。
** 请注意,Input
Facade 有额外的方法 get()可用。
关于php - 在 Laravel 4 中上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18204781/