сильный текст < /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
Как создать API для Excel загрузку с Laravel 5.7 ⇐ Php
Кемеровские программисты php общаются здесь
-
Anonymous
1739403167
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');
Подробнее здесь: [url]https://stackoverflow.com/questions/55068452/how-to-create-an-api-for-excel-upload-with-laravel-5-7[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия