chenqp hace 1 año
padre
commit
a03b3ce73c
Se han modificado 1 ficheros con 139 adiciones y 120 borrados
  1. 139 120
      app/Service/ImportService.php

+ 139 - 120
app/Service/ImportService.php

@@ -28,6 +28,13 @@ class ImportService extends Service
 
     const string = '/api/getFile/';
 
+    const file_one = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
+    const file_two = 'application/zip';
+    const file_array = [
+        self::file_one,
+        self::file_two,
+    ];
+
     //文件类型
     const FILE_TYPE = [
         'txt',
@@ -102,6 +109,138 @@ class ImportService extends Service
     public function getFileData($data){
         if(empty($data['url'])) return [false, '文件路径不能为空'];
 
+        try {
+            // 发送 HTTP 请求获取文件内容
+            $response = file_get_contents($data['url']);
+        } catch (\Throwable $exception) {
+            if (str_contains($exception->getMessage(), 'failed to open stream')) return [false, "URL链接已失效"];
+            return [false, $exception->getMessage()];
+        }
+        if ($response === false) return [false, '文件获取失败'];
+
+        // 创建一个临时文件资源
+        $tempFile = tempnam(sys_get_temp_dir(), 'download_');
+        file_put_contents($tempFile, $response);
+
+        // 判断文件类型
+        $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
+        $mimeType = finfo_file($fileInfo, $tempFile);
+        finfo_close($fileInfo);
+        if(! in_array($mimeType, self::file_array)) return [false, '文件类型目前暂时支持zip|xlsx'];
+
+        // 根据文件类型处理
+        if ($mimeType === self::file_one) {
+            // 处理单个XLSX文件
+            list($status,$result) = $this->processXlsxFile($tempFile);
+            if (! $status) return [false, $result];
+
+            return [true, ['xlsx' => $result]];
+        } elseif ($mimeType === self::file_two) {
+            // 创建 ZipArchive 对象
+            $zip = new \ZipArchive();
+            if ($zip->open($tempFile) !== true) {
+                // 删除临时文件
+                unlink($tempFile);
+                return [false, '无法打开ZIP文件'];
+            }
+
+            // 初始化一个数组来存储所有XLSX文件的数据
+            $allFilesData = [];
+
+            // 遍历ZIP文件中的每一个文件
+            for ($i = 0; $i < $zip->numFiles; $i++) {
+                $filename = $zip->getNameIndex($i);
+
+                if (pathinfo($filename, PATHINFO_EXTENSION) === 'xlsx') {// 检查是否为XLSX文件
+                    // 提取文件到临时位置
+                    $tempXlsxFile = tempnam(sys_get_temp_dir(), 'xlsx_');
+
+                    // 提取文件到临时位置
+                    if ($zip->extractTo(sys_get_temp_dir(), [$filename]) === false) {
+                        continue; // 跳过提取失败的文件
+                    }
+
+                    // 获取提取出的文件的实际路径
+                    $extractedFile = sys_get_temp_dir() . '/' . basename($filename);
+
+                    // 检查临时文件是否存在
+                    if (! file_exists($extractedFile)) continue;
+
+                    // 重命名提取出的文件为临时文件
+                    if (!rename($extractedFile, $tempXlsxFile)) {
+                        continue;
+                    }
+
+                    list($status,$xlsxData) = $this->processXlsxFile($tempXlsxFile);
+                    if (! $status) return [false, $xlsxData];
+
+                    // 将当前XLSX文件的数据添加到所有文件的数据数组中
+                    $xlsxData['filename'] = $filename;
+                    $allFilesData[] = $xlsxData;
+                }
+            }
+
+            // 关闭 ZIP 文件
+            $zip->close();
+
+            // 删除临时 ZIP 文件
+            unlink($tempFile);
+
+            return [true, ["zip" => $allFilesData]];
+        } else {
+            // 删除临时文件
+            unlink($tempFile);
+            return [false, '不支持的文件类型'];
+        }
+    }
+
+    // 定义一个函数来处理XLSX文件
+    function processXlsxFile($filename) {
+        try {
+            if (is_file($filename)) {
+                chmod($filename, 0777);
+            }
+
+            // 使用 PhpSpreadsheet 读取文件
+            $reader = IOFactory::createReader('Xlsx');
+            $spreadsheet = $reader->load($filename);
+
+            // 初始化一个数组来存储所有工作表的数据
+            $allSheetData = [];
+
+            // 遍历所有工作表
+            foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
+                $sheetData = [];
+                foreach ($worksheet->getRowIterator() as $row) {
+                    $cellIterator = $row->getCellIterator();
+                    $cellIterator->setIterateOnlyExistingCells(false); // 循环所有单元格,即使它未设置
+                    $rowData = [];
+
+                    foreach ($cellIterator as $cell) {
+                        $rowData[] = $cell->getValue();
+                    }
+
+                    $sheetData[] = $rowData;
+                }
+
+                // 将当前工作表的数据添加到总数据数组中
+                $allSheetData[$worksheet->getTitle()] = $sheetData;
+            }
+            // 删除临时文件
+            unlink($filename);
+
+            return [true, $allSheetData];
+
+        } catch (\Throwable $e) {
+            // 删除临时文件
+            unlink($filename);
+            return [false, "处理文件 {$filename} 时发生错误: " . $e->getMessage()];
+        }
+    }
+
+    public function getFileData1($data){
+        if(empty($data['url'])) return [false, '文件路径不能为空'];
+
         try{
             // 发送 HTTP 请求获取文件内容
             $response = file_get_contents($data['url']);
@@ -154,125 +293,5 @@ class ImportService extends Service
 
         return [true , $allSheetData];
     }
-
-    public function saveFile1($data){
-        if(empty($data['url'])) return [false, '文件路径不能为空'];
-
-        $this->downloadFile($data['url']);
-    }
-
-    public function downloadFile($url)
-    {
-        // 发送 HEAD 请求获取响应头
-        $ch = curl_init();
-        curl_setopt($ch, CURLOPT_URL, $url);
-        curl_setopt($ch, CURLOPT_NOBODY, true); // 只获取头部信息
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-        curl_setopt($ch, CURLOPT_HEADER, true);
-        curl_setopt($ch, CURLOPT_FAILONERROR, true);
-        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间
-        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3');
-        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证(仅用于测试)
-        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略 SSL 主机验证(仅用于测试)
-        curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细调试信息
-
-        // 打开一个文件句柄来捕获调试信息
-        $verbose = fopen('php://temp', 'w+');
-        curl_setopt($ch, CURLOPT_STDERR, $verbose);
-
-        // 执行请求
-        $response = curl_exec($ch);
-        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-        $error = curl_error($ch);
-
-        // 读取调试信息
-        rewind($verbose);
-        $verboseLog = stream_get_contents($verbose);
-        fclose($verbose);
-
-        if ($response === false || $httpCode !== 200) {
-            curl_close($ch);
-            return [false, '打开URL下的文件内容失败,请更换URL'];
-        }dd($response);
-
-        // 获取 Content-Disposition
-        $contentDisposition = null;
-        $headers = explode("\r\n", $response);
-        foreach ($headers as $headerLine) {
-            if (strpos($headerLine, 'Content-Disposition:') === 0) {
-                $contentDisposition = trim(str_replace('Content-Disposition:', '', $headerLine));
-                break;
-            }
-        }dd($headers);
-
-        if ($contentDisposition === null) {
-            curl_close($ch);
-            return response()->json(['error' => 'Failed to determine file name from Content-Disposition'], 500);
-        }
-
-        // 从 Content-Disposition 中提取文件名
-        preg_match('/fileName="?([^"]+)"?/', $contentDisposition, $matches);
-        if (empty($matches)) {
-            curl_close($ch);
-            return response()->json(['error' => 'Failed to extract file name from Content-Disposition'], 500);
-        }
-
-        $filename = urldecode($matches[1]);
-        $extension = pathinfo($filename, PATHINFO_EXTENSION);
-dd($extension);
-        if ($extension === '') {
-            curl_close($ch);
-            return response()->json(['error' => 'Failed to determine file extension'], 500);
-        }
-
-        // 关闭 cURL 资源
-        curl_close($ch);
-
-        // 发送 GET 请求获取文件内容
-        $ch = curl_init();
-        curl_setopt($ch, CURLOPT_URL, $url);
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-        curl_setopt($ch, CURLOPT_FAILONERROR, true);
-        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间
-        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3');
-        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证(仅用于测试)
-        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略 SSL 主机验证(仅用于测试)
-
-        // 执行请求
-        $response = curl_exec($ch);
-        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-        $error = curl_error($ch);
-
-        if ($response === false || $httpCode !== 200) {
-            curl_close($ch);
-            return response()->json(['error' => 'Failed to download file: HTTP status code ' . $httpCode . ', Error: ' . $error], 500);
-        }
-
-        // 关闭 cURL 资源
-        curl_close($ch);
-
-        // 将文件内容保存到本地存储
-        Storage::put($filename, $response);
-
-        return response()->json(['message' => 'File downloaded and saved successfully', 'file' => $filename]);
-    }
-
-    private function getFileTypeExtension($contentType)
-    {
-        $mimeTypeMap = [
-            'application/pdf' => 'pdf',
-            'application/msword' => 'doc',
-            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
-            'application/vnd.ms-excel' => 'xls',
-            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
-            'image/jpeg' => 'jpg',
-            'image/png' => 'png',
-            'image/gif' => 'gif',
-            'text/plain' => 'txt',
-            // 添加其他 MIME 类型和扩展名映射
-        ];
-
-        return isset($mimeTypeMap[$contentType]) ? $mimeTypeMap[$contentType] : null;
-    }
 }