如何解决Angular - 如何通过 Laravel api 上传/导入 excel
我从未在普通的 Laravel 中做过这件事,但我只在 Laravel 中做过。我正在使用 Angular-12 和 Laravel-8 Maatwebsite 进行一个项目。我有这张桌子:
型号
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $table = 'students';
protected $fillable = [
'user_id','school_id','class_id','phone','father','mother','work_father','work_mother','phone_father','phone_mother','generation'
];
}
进口:
命名空间 App\Imports;
use App\Models\ScStudent;
use Maatwebsite\Excel\Concerns\ToModel;
class StudentImport implements ToModel
{
public function model(array $row)
{
return new ScStudent([
'id' => rand(100000,1000000),'user_id' => $row[0],'school_id' => $row[1],'class_id' => $row[2],'phone' => $row[3],'father' => $row[4],'mother' => $row[5],'work_father' => $row[6],'work_mother' => $row[7],'phone_father' => $row[8],'phone_mother' => $row[9],'generation' => $row[10]
]);
}
}
控制器:
public function import(Request $request,$user)
{
$validator = Validator::make($request->all(),[
'import' => 'file|mimes:xls,xlsx|max:5000',]);
if($validator->fails()) {
return response()->json(['message' => $validator->errors()],401);
} else {
$check = User::where('id',$user)->pluck('id');
if($check[0] !== null || $check[0] !== undefined) {
$file = $request->file('import');
$file->move(storage_path('app/public/office'),$file->getClientOriginalName());
Excel::import(new StudentImport,storage_path('app/public/office/' . $file->getClientOriginalName() ));
return response()->json(['message' => 'Successfuly import data'],200);
} else {
return response()->json(['message' => 'Not allowed'],401);
}
}
}
路由(api):
Route::post('student/excel/import/{any}','StudentController@import')->name('student.import');
如何编写 Angular 前端以导入数据库
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。