Как создать API для Excel загрузку с Laravel 5.7Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Как создать API для Excel загрузку с Laravel 5.7

Сообщение Anonymous »

сильный текст < /strong>
Я хочу создать простой API, который позволит мне загрузить файл Excel и вставить его в мою базу данных с использованием Laravel 5.7 и Vue. Когда я попытался позвонить в это через почтальон или VUE, он продолжает бросить ошибку 500 Ошибка внутреннего сервера при отправке. Вот моя функция контроллера ниже: < /p>

//Upload Students
public function postUploadSudents( Request $request ) {

if ( $request->hasFile( 'file' ) ) {
$fileName = Carbon::now()->timestamp . $request->file( 'file' )->getClientOriginalName();
$request->file( 'file' )->move( 'uploads/students', $fileName );
$fileUrl = url( 'uploads/students/' . $fileName );
} else {
session()->flash( 'error', 'Please attach a file.' );

return redirect()->back();
}

try {

$downloadUrl = url( "/uploads/students/" . $fileName );

/* Identify file, create reader and load file */
$inputFileType = PHPExcel_IOFactory::identify( getcwd() . "/" . "uploads/students/" . $fileName );
$objReader = PHPExcel_IOFactory::createReader( $inputFileType );
$objPHPExcel = PHPExcel_IOFactory::load( getcwd() . "/" . "uploads/students/" . $fileName );

$sheet = $objPHPExcel->getActiveSheet();
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$time_pre = microtime( true );

// Read a row of data into an array
$rowData = $sheet->rangeToArray( 'A2:' . $highestColumn . $highestRow,
null, false, false );

$count = 0;

$failedImports = array();

DB::beginTransaction();
// add students to database from file
foreach ( $rowData as $cell ) {
$count ++;
try {

$date = "";
$dateCell = $objPHPExcel->getActiveSheet()->getCell( 'G' . ( $count + 1 ) );
$invalidDate = $objPHPExcel->getActiveSheet()->getCell( 'G' . ( $count + 1 ) )->getValue();
if ( PHPExcel_Shared_Date::isDateTime( $dateCell ) ) {
$date = date( "d-m-Y", PHPExcel_Shared_Date::ExcelToPHP( $invalidDate ) );
}

$student = new StudentRecord();
$student->first_name = $cell[0];
$student->last_name = $cell[1];
$student->matric_number = $cell[2];
$student->registration_number = $cell[4];
$student->level = $cell[5];
$student->department = $cell[6];
$student->date_of_birth = $date;
$student->nationality = $cell[8];
$student->state_of_origin = $cell[9];
$student->lga = $cell[10];
$student->email = strtolower($cell[11]);
// $student->password = bcrypt( "fuaa123" );
$student->dashboard_number = $cell[12];
$student->phone_number = $cell[13];
$student->home_address = $cell[14];
$student->ip_address = $cell[15];

$student->save();

} catch ( \Exception $e ) {
return $e->getMessage();
array_push( $failedImports, $count );
}

}

DB::commit();
if ( count( $failedImports ) > 0 ) {
$error = "";
foreach ( $failedImports as $item ) {
$error .= ",$item";
}

$failed = count( $failedImports );
// session()->flash( 'error', "$failed did not import. [$error] " );

// an alternative to session flash above
return response(array("message" => "Failed did not import", "data" => $failed), 406);

}

//$number = $count - count( $failedImports );
//$request->session()->flash( "success", "$count records in total. $number uploaded." );

// return redirect()->back();

return response(array("message"=>"Successful", "data" => $student), 200);

} catch ( \Exception $exception ){

return response (array(["message"=>"Something went wrong. Please try again", $exception]),400);

// session()->flash('error','Something went wrong. Please try again.');
// return redirect()->back();
}

}
< /code>

и мой api.php route ссылка: < /p>

//StudentRecords Upload Routes
Route::post('/uploadStudents','StudentRecordController@postUploadSudents');



Подробнее здесь: https://stackoverflow.com/questions/550 ... aravel-5-7
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»