企微短剧业务系统

ImportService.php 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: shensong
  5. * Date: 2022/6/8
  6. * Time: 17:01
  7. */
  8. namespace App\Service;
  9. use App\Log;
  10. use Illuminate\Support\Facades\Storage;
  11. class ImportService
  12. {
  13. public static function importExcel($file, $corpid, $importType)
  14. {
  15. $admin = \Auth::user();
  16. $adminId = $admin->id;
  17. $requestData = [
  18. 'file' => (array) $file,
  19. 'corpid' => $corpid,
  20. 'import_type' => $importType,
  21. 'admin' => (array) $admin,
  22. ];
  23. $extArr = ['xlsx', 'xls', 'csv'];
  24. try{
  25. // 验证文件后缀是否合法
  26. $ext = strtolower($file->getClientOriginalExtension());
  27. if(!in_array($ext, $extArr)) {
  28. Log::logInfo('batchAddCustomerImport 参数:'.json_encode($requestData, 256), [
  29. '文件格式不合法',
  30. ], 'interface');
  31. return [['error' => '文件格式不合法'], 1102];
  32. }
  33. $fileName = self::getFileNameByType($importType, $corpid, $adminId, $ext);
  34. if(empty($fileName)) {
  35. Log::logError('importExcel 参数:'.json_encode($requestData, 256), ['文件导入类型不合法'], 'interface');
  36. return [['error' => '文件导入类型不合法'], 1102];
  37. }
  38. // 将文件保存到服务器
  39. $originalFileName = $file->getClientOriginalName();
  40. $realPath = $file->getRealPath();
  41. $result = Storage::disk('uploads')->put($fileName, file_get_contents($realPath));
  42. if(!$result) {
  43. Log::logError('importExcel 参数:'.json_encode($requestData, 256), ['保存文件失败'], 'interface');
  44. return [['error' => '保存文件失败'], 2304];
  45. }
  46. $fileResult['original_file_name'] = $originalFileName;
  47. $fileResult['ext'] = $ext;
  48. $fileResult['new_file_name'] = $fileName;
  49. return [$fileResult, 0];
  50. } catch (\Exception $exception) {
  51. # 打印错误日志
  52. Log::logError('importExcel 参数:'.json_encode($requestData, 256), [
  53. 'file' => $exception->getFile(),
  54. 'line' => $exception->getLine(),
  55. 'message' => $exception->getMessage(),
  56. 'trace' => $exception->getTraceAsString(),
  57. ], 'interface');
  58. return [['error' => '请求失败,请联系管理员'], 400];
  59. }
  60. }
  61. public static function getFileNameByType($importType, $corpid, $userId, $ext)
  62. {
  63. switch($importType){
  64. case 1:
  65. $fileName = 'batch_add_customer_import_'.$userId.'_'.$corpid.'_'.time().'_'.random_int(1, 9999).'.'.$ext;
  66. break;
  67. default:
  68. $fileName = null;
  69. break;
  70. }
  71. return $fileName;
  72. }
  73. }