php 在 Laravel 4 中上传多个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18204781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:09:24  来源:igfitidea点击:

Upload multiple files in Laravel 4

phpfileuploadlaravel

提问by richa

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.

这是我用于上传多个文件的控制器代码,我正在从 Google Chrome 上的“邮递员”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);
                }
            }
        }
    }  
}

I have tried this code also but it returns me location of a file in temporary folder

我也试过这段代码,但它返回了我在临时文件夹中的文件位置

$file = Input::file('file');
            echo count($file);

and echo count($_FILES['file']);returns me always 5.Can anyone tell me why?

并且 echo count($_FILES['file']);总是返回我 5.谁能告诉我为什么?

and why foreach(Input::file('file') as $key => $abc)gives the error invalid arguments

以及为什么foreach(Input::file('file') as $key => $abc)给出错误无效参数

回答by fideloper

Solution:

解决方案:

You can get all files by simply doing:

您只需执行以下操作即可获取所有文件:

$allFiles = Input::file();

Explanation:

解释:

The class Inputis actually a Facade for the Illuminate\Http\Requestclass (Yes, just like the Requestfacade - they both serve as the "Face" for the same class!**).

该类Input实际上是该类的 Facade Illuminate\Http\Request(是的,就像RequestFacade - 它们都充当同一类的“Face”!**)。

That means you can use any methods available in Request .

这意味着您可以使用 Request 中可用的任何方法。

If we search for the function file(), we see it works like this:

如果我们搜索 function file(),我们会看到它是这样工作的:

public function file($key = null, $default = null)
{
    return $this->retrieveItem('files', $key, $default);
}

Now, retrieveItem()is a protected method, so we can't just call it from our Controller directly. Looking deeper, however, we see that we can pass the file()method "null"for the key. If we do so, then we'll get all the items!

现在,retrieveItem()是一个受保护的方法,所以我们不能直接从我们的控制器中调用它。然而,更深入地看,我们看到我们可以file()为键传递方法“null”。如果我们这样做,那么我们将获得所有物品!

protected function retrieveItem($source, $key, $default)
{
    if (is_null($key))
    {
        return $this->$source->all();
    }
    else
    {
        return $this->$source->get($key, $default, true);
    }
}

So, if we call Input::file(), the Request class will internally run $this->retrieveItem('files', null, null)which will in turn run return $this->files->all();and we will get all the files uploaded.

因此,如果我们调用Input::file(),Request 类将在内部运行$this->retrieveItem('files', null, null),该类将依次运行return $this->files->all();,我们将上传所有文件。

** Note that InputFacade has the extra method get()available in it.

** 请注意,InputFacade 中有一个额外的方法get()可用。

回答by Andreyco

Not using any API, but this might outline the principle.

不使用任何 API,但这可能会概述原理。

I set up this routes.php file, whick will help you with upload test.

我设置了这个 routes.php 文件,它将帮助您进行上传测试。

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();
});

Notice the input name, files[]:If uploading multiple files under the same name, include brackets as well.

注意输入名称,files[]:如果以相同的名称上传多个文件,也包括括号。

回答by ctf0

the above solutions wont work with multiple files as the return will fire as soon the first item gets validated ,so here is a solution after several hours of head-wall banging. inspired by https://www.youtube.com/watch?v=PNtuds0l8bA

上述解决方案不适用于多个文件,因为一旦第一个项目得到验证,返回就会触发,所以这是几个小时的头墙撞击后的解决方案。灵感来自https://www.youtube.com/watch?v=PNtuds0l8bA

// route
Route::get('/', function() {
    return View::make('main');
});
Route::post('up', 'FUplaodController@store');

// controller
class FUplaodController extends \BaseController {
    public function store()
    {
        if (Input::hasFile('images'))
        {
            $files = Input::file('images');
            $rules = [
                'file' => 'required|image'
            ];
            $destinationPath = public_path().'/uploads';

            foreach ($files as $one)
            {
                $v = Validator::make(['file' => $one], $rules);
                if ($v->passes())
                {
                    $filename       = $one->getClientOriginalName();
                    $upload_success = $one->move($destinationPath, $filename);
                    if ($upload_success)
                    {
                        $done[] = $filename;
                        Session::flash('done', $done);
                    }
                }
                else
                {
                    $filename = $one->getClientOriginalName();
                    $not[] = $filename;
                    Session::flash('not', $not);
                }
            }
            return Redirect::back()->withErrors($v);
        }
        return Redirect::back()->withErrors('choose a file');
    }
}

// view
<!-- uploaded -->
@if (Session::has('done'))
    @foreach (Session::get('done') as $yes)
        <li>{{ $yes }}</li>
    @endforeach
    <p style="color: #2ecc71">Uploaded</p>
    <br>
@endif

<!-- not uploaded -->
@if (Session::has('not'))
    @foreach (Session::get('not') as $no)
        <li>{{ $no }}</li>
    @endforeach
    <p style="color: #c0392b">wasnt uploaded</p>
    <br>
@endif

<!-- errors -->
<p style="color: #c0392b">{{ $errors->first() }}</p>
<hr>

<!-- form -->
{{ Form::open(['url' => 'up', 'files'=>true]) }}
    {{ Form::file('images[]', ['multiple'=>true]) }}
    {{ Form::submit('Upload') }}
{{ Form::close() }}

u basicly save the filenames in an array and pass those arrays to a session then only add returnwhen the loop has finished.

你基本上将文件名保存在一个数组中并将这些数组传递给一个会话,然后只return在循环完成时添加。

回答by Vishal Tarkar

1. Form :-Form opening tag must have ‘files'=>true and file field must have name [](with array) and ‘multiple'=>true

1. 表单:-表单开始标签必须有'files'=>true 并且文件字段必须有名称[](with array) 和'multiple'=>true

<?php 
{{ Form::open(array('url'=>'apply/multiple_upload','method'=>'POST', 'files'=>true)) }}
{{ Form::file('images[]', array('multiple'=>true)) }}
?>

2. Add below code to your controller function :-

2. 将以下代码添加到您的控制器功能中:-

<?php
// getting all of the post data
$files = Input::file('images');
foreach($files as $file) {
  // validating each file.
  $rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
  $validator = Validator::make(array('file'=> $file), $rules);
  if($validator->passes()){
    // path is root/uploads
    $destinationPath = 'uploads';
    $filename = $file->getClientOriginalName();
    $upload_success = $file->move($destinationPath, $filename);
    // flash message to show success.
    Session::flash('success', 'Upload successfully'); 
    return Redirect::to('upload');
  } 
  else {
    // redirect back with errors.
    return Redirect::to('upload')->withInput()->withErrors($validator);
  }
}
?>

SOURCE : http://tutsnare.com/upload-multiple-files-in-laravel/

来源:http: //tutsnare.com/upload-multiple-files-in-laravel/

EDIT: Reference source link is not working.

编辑:参考源链接不起作用