44
55namespace BusinessG \HyperfExcel \Http \Controller ;
66
7+ use BusinessG \BaseExcel \Contract \FilesystemResolverInterface ;
78use BusinessG \BaseExcel \Service \ExcelBusinessService ;
9+ use Hyperf \Contract \ConfigInterface ;
810use Hyperf \HttpServer \Contract \RequestInterface ;
911use Hyperf \HttpServer \Contract \ResponseInterface ;
1012use Psr \Container \ContainerInterface ;
@@ -15,6 +17,7 @@ class ExcelController
1517 public function __construct (
1618 protected ContainerInterface $ container ,
1719 protected ExcelBusinessService $ service ,
20+ protected FilesystemResolverInterface $ filesystemResolver ,
1821 protected RequestInterface $ request ,
1922 protected ResponseInterface $ response
2023 ) {
@@ -89,14 +92,19 @@ public function upload(): PsrResponseInterface
8992 return $ this ->response ->json ($ this ->service ->errorResponse (422 , '仅支持 xlsx, xls 格式 ' ));
9093 }
9194
92- $ dir = BASE_PATH . '/runtime/excel-import/ ' . date ('Y/m/d ' );
93- if (!is_dir ($ dir )) {
94- mkdir ($ dir , 0777 , true );
95+ $ config = $ this ->container ->get (ConfigInterface::class);
96+ $ uploadDisk = $ config ->get ('excel.http.upload.disk ' , 'local ' );
97+ $ uploadDir = $ config ->get ('excel.http.upload.dir ' , 'excel-import ' );
98+ $ relativePath = $ uploadDir . '/ ' . date ('Y/m/d ' ) . '/ ' . bin2hex (random_bytes (20 )) . '. ' . $ extension ;
99+
100+ $ filesystem = $ this ->filesystemResolver ->getFilesystem ($ uploadDisk );
101+ $ stream = fopen ($ file ->getRealPath (), 'r ' );
102+ $ filesystem ->writeStream ($ relativePath , $ stream );
103+ if (is_resource ($ stream )) {
104+ fclose ($ stream );
95105 }
96106
97- $ fileName = bin2hex (random_bytes (20 )) . '. ' . $ extension ;
98- $ fullPath = $ dir . '/ ' . $ fileName ;
99- $ file ->moveTo ($ fullPath );
107+ $ fullPath = $ this ->getUploadFullPath ($ config , $ uploadDisk , $ relativePath );
100108
101109 return $ this ->response ->json (
102110 $ this ->service ->successResponse ([
@@ -105,4 +113,13 @@ public function upload(): PsrResponseInterface
105113 ])
106114 );
107115 }
116+
117+ protected function getUploadFullPath (ConfigInterface $ config , string $ disk , string $ relativePath ): string
118+ {
119+ $ root = $ config ->get ('file.storage. ' . $ disk . '.root ' );
120+ if ($ root !== null && $ root !== '' ) {
121+ return rtrim ($ root , '/ \\' ) . DIRECTORY_SEPARATOR . str_replace ('/ ' , DIRECTORY_SEPARATOR , $ relativePath );
122+ }
123+ return $ relativePath ;
124+ }
108125}
0 commit comments