1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <?php
- /**
- * Created by PhpStorm.
- * User: shensong
- * Date: 2022/6/8
- * Time: 17:01
- */
- namespace App\Service;
- use App\Log;
- use Illuminate\Support\Facades\Storage;
- class ImportService
- {
- public static function importExcel($file, $corpid, $importType)
- {
- $admin = \Auth::user();
- $adminId = $admin->id;
- $requestData = [
- 'file' => (array) $file,
- 'corpid' => $corpid,
- 'import_type' => $importType,
- 'admin' => (array) $admin,
- ];
- $extArr = ['xlsx', 'xls', 'csv'];
- try{
- // 验证文件后缀是否合法
- $ext = strtolower($file->getClientOriginalExtension());
- if(!in_array($ext, $extArr)) {
- Log::logInfo('batchAddCustomerImport 参数:'.json_encode($requestData, 256), [
- '文件格式不合法',
- ], 'interface');
- return [['error' => '文件格式不合法'], 1102];
- }
- $fileName = self::getFileNameByType($importType, $corpid, $adminId, $ext);
- if(empty($fileName)) {
- Log::logError('importExcel 参数:'.json_encode($requestData, 256), ['文件导入类型不合法'], 'interface');
- return [['error' => '文件导入类型不合法'], 1102];
- }
- // 将文件保存到服务器
- $originalFileName = $file->getClientOriginalName();
- $realPath = $file->getRealPath();
- $result = Storage::disk('uploads')->put($fileName, file_get_contents($realPath));
- if(!$result) {
- Log::logError('importExcel 参数:'.json_encode($requestData, 256), ['保存文件失败'], 'interface');
- return [['error' => '保存文件失败'], 2304];
- }
- $fileResult['original_file_name'] = $originalFileName;
- $fileResult['ext'] = $ext;
- $fileResult['new_file_name'] = $fileName;
- return [$fileResult, 0];
- } catch (\Exception $exception) {
- # 打印错误日志
- Log::logError('importExcel 参数:'.json_encode($requestData, 256), [
- 'file' => $exception->getFile(),
- 'line' => $exception->getLine(),
- 'message' => $exception->getMessage(),
- 'trace' => $exception->getTraceAsString(),
- ], 'interface');
- return [['error' => '请求失败,请联系管理员'], 400];
- }
- }
- public static function getFileNameByType($importType, $corpid, $userId, $ext)
- {
- switch($importType){
- case 1:
- $fileName = 'batch_add_customer_import_'.$userId.'_'.$corpid.'_'.time().'_'.random_int(1, 9999).'.'.$ext;
- break;
- default:
- $fileName = null;
- break;
- }
- return $fileName;
- }
- }
|