setReadDataOnly(true); // 只读取有数据的单元格 // $spreadsheet = $reader->load($data['file']); // dd($spreadsheet); // // 创建一个Reader对象 // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader // //// 加载Excel文件 // $spreadsheet = $reader->load($data['file']); // //// 获取第一个工作表 // $worksheet = $spreadsheet->getActiveSheet(); // //// 获取总行数 // $totalRows = $worksheet->getHighestRow();dd($totalRows); if(empty($data['file'])) return [false,'导入文件不能为空']; try { $this->uploadFile($data['file']); }catch (\Throwable $exception) { return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')']; } return [true, '']; } public function uploadFile($file){ if(empty($file)) return [false, '请上传文件']; // 获取文件相关信息 $ext = $file->getClientOriginalExtension(); // 扩展名 $realPath = $file->getRealPath(); //临时文件的绝对路径 $ext = strtolower($ext); if (! in_array($ext, self::FILE_TYPE)){ $str = '文件格式为:'; foreach (self::FILE_TYPE as $value){ $str.= $value . ' ' ; } return [false, $str]; } $date = date("Y-m-d"); //文件名 $file_name = date("Ymd").time().rand(1000,9999); $filename = $file_name.'.' . $ext; $dir = self::tmp_dir . '/' . $date . '/' . $filename; Storage::disk('public')->put($dir, file_get_contents($realPath)); return [true, self::string . $filename]; } public function getFileData($data){ if(empty($data['url'])) return [false, '文件路径不能为空']; try{ // 发送 HTTP 请求获取文件内容 $response = file_get_contents($data['url']); }catch (\Throwable $exception){ return [false, $exception->getMessage()]; } if ($response === false) return [false, '文件获取失败']; // 创建一个临时文件资源 $tempFile = tempnam(sys_get_temp_dir(), 'xlsx_'); file_put_contents($tempFile, $response); // 使用 phpspreadsheet 读取文件 try { // 创建一个 Xlsx 读取器 $reader = IOFactory::createReader('Xlsx'); // 加载临时文件 $spreadsheet = $reader->load($tempFile); // 初始化一个数组来存储所有工作表的数据 $allSheetData = []; // 遍历所有工作表 foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $sheetData = []; foreach ($worksheet->getRowIterator() as $row) { $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set $rowData = []; foreach ($cellIterator as $cell) { $rowData[] = $cell->getValue(); } $sheetData[] = $rowData; } // 将当前工作表的数据添加到总数据数组中 $allSheetData[$worksheet->getTitle()] = $sheetData; } // 删除临时文件 unlink($tempFile); } catch (\Exception $e) { // 删除临时文件 unlink($tempFile); return [false, $e->getMessage()]; } 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; } }