在 laravel 中上传时如何验证 csv 文件?

how to validate the csv file while uploading in laravel?

我正在使用 laravel 框架 5.2。我正在使用 Maatwebsite Excel 软件包,我已成功安装并成功导入 CSV 格式文件,但问题是:

假设我有一个 table 列是:

Table_name:- employees_schedule 
   columns:- user_id, customer_name, date,

现在当我上传包含三列的 CSV 文件时 (user_id, customer_name, date) 它已成功上传。

当我上传 CSV 格式文件时,使用附加列示例 (user_id, customer_name, date, hacking_column, time) 我需要显示一条错误消息,例如 "Your CSV files has some unwanted columns"

谁能帮帮我。这是我的函数

public function UploadSchedule (Request $request)
{
    if ($request->isMethod('post')) {

        $data = $request->all();

        //echo "<pre>"; print_r($data); die;

        Excel::load(Input::file('schedule'), function ($reader) {
            $reader->each(function ($sheet) {
                EmployeeSchedule::firstOrCreate($sheet->toArray());
            });
        });

        return redirect()
            ->back()
            ->with(
                'flash_message_success', 
                'Your Employee Schedule Uploaded successfully!'
            );
    }
}

和blade文件:-

<form id="addForm" role="form" class="form-horizontal" method="post"
  action="{{ url('admin/upload-employee-schedule') }}" 
  enctype="multipart/form-data">

  <input type="hidden" name="_token" value="{{{ csrf_token() }}}"/>

  <div class="form-body">
    <div class="form-group">
        <label class="col-md-3 control-label">Upload Schedule:</label>
        <div class="col-md-5">
            <input type="file" id="csv" name="schedule">
        </div>
    </div>
  </div>

  <div class="form-actions right1 text-center">
    <button id="check" class="btn green" type="submit">Submit</button>
  </div>
</form>

在这里我找到了自己的解决方案。我只是打开文件并获得第一个 header 行。这是我的片段:-

public function UploadSchedule(Request $request){
if($request->isMethod('post')){
    $data = $request->all();
    $file = Input::file('schedule');
    $handle = fopen($file,"r");
    $header = fgetcsv($handle, 0, ',');
    $countheader= count($header); 
    if($countheader<4  && in_array('user_id',$header) && in_array('customer_name',$header) && in_array('date',$header)){
        Excel::load($file ,function($reader){
            $reader->each(function($sheet){
                $sheet['date'] = date('Y-m-d',strtotime($sheet['date']));
                EmployeeSchedule::firstOrCreate($sheet->toArray());
            });
        });
    } else {
        return redirect()->back()->with('flash_message_error', 'Your CSV files having unmatched Columns to our database...Your columns must be in this sequence <strong> user_id,customer_name,date </strong> only');
    }
    return redirect()->back()->with('flash_message_success', 'Your Employee Schedule Uploaded successfully!');

}

你也可以看看下面的url

https://www.grok-interactive.com/blog/import-large-csv-into-mysql-with-php-part-2-csv-file-validation/

我知道这是一个旧线程,但我认为它值得重新访问。希望它能帮助一些可怜的灵魂解析 SO 来解决这个确切的问题。您可以使用 Maatwebsite/Excel 2.1.0 for this

(Laravel 5.7) 您的函数正在做很多事情——您应该将验证和加载函数分开。将使它更容易测试。

例如:

public function uploadSchedule(Request $request)
{
        // Validate request 
        $request->validate([
            'import_file' => 'required|mimes:csv,txt',
        ]);

        $data = $this->fetchCsv($request); // Fetch the CSV data 
        $headerRow = $data->first()->keys()->toArray(); // Fetch the header row
        $validate = $this->validateHeaderRow($headerRow); // Filter it through our validation 

        // If our header row passed validation 
        if( $validate == true )
        {
            // Load $data into array if > 0 
            if($data->count()){
                $arr = $this->loadCsvIntoArray($data, $request);

                // Write to the database 
                if(!empty($arr)){
                    EmployeeSchedule::insert($arr);
                }
            }

        }

        // Return our import finished message
        $message = $this->returnMessage($validate, $request);
        return $message;
}

fetchCSV():

// Return a schedule CSV
public function fetchCsv($request)
{
    $path = $request->file('import_file')->getRealPath();
    $data = Excel::load($path)->get();

    return $data;
}

validateHeaderRow($headerRow):

public function validateHeaderRow($headerRow)
{
    $validate = false;

    if( $headerRow[0] == 'user_id'
        && $headerRow[1] == 'customer_name' 
        && $headerRow[2] == 'date' )

        {
            $validate = true;
        } 

    return $validate;

}

loadCsvIntoArray($data, $request):

// Load the import .CSV data into an array
public function loadCsvIntoArray($data, $request)
{

    foreach ($data as $key => $value) {
        $arr[] = [
            'user_id' => $value->user_id,
            'customer_name' => $value->customer_name,
            'date' => $value->date,
        ];
    }

    return $arr;
}

returnMessage($validate, $request):

// Fetch our message to display to user after import 
public function returnMessage($validate, $request)
{
    if( $validate == true )
    { 
        return back()->with('success', 'Schedule uploaded successfully!');
    } else {
        return back()->with('danger', 'Your .CSV headers do not meet the requirements. Must be: `user_id`, `customer_name`, `date`');
    }
}