json([ 'error' => "Error: Failed to fetch file (HTTP Code: {$httpCode}). " . ($curlError ? " cURL Error: {$curlError}" : '') ], $httpCode); } // Determine the filename for download $filename = basename($filePath); // Return the file content with download headers return response($response, 200) ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'application/octet-stream') ->header('Content-Disposition', "attachment; filename=\"{$filename}\"") ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate') ->header('Pragma', 'public') ->header('Content-Length', strlen($response)); } public function preview($file) { $filePath = base64_decode($file); $baseUrl = rtrim(env('NEXT_CLOUD_URL'), '/'); $username = env('NEXT_CLOUD_USERNAME'); $password = env('NEXT_CLOUD_PASSWORD'); $filePath = trim((string) $filePath); $segments = explode('/', ltrim($filePath, '/')); $encodedPath = implode('/', array_map('rawurlencode', $segments)); $relativePath = "remote.php/dav/files/{$username}/" . $encodedPath; $url = $baseUrl . '/' . $relativePath; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, "{$username}:{$password}"); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $response = curl_exec($ch); if ($response === false) { curl_close($ch); abort(404); } $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); if ($statusCode >= 400 || !$response) { abort(404); } if (!$contentType) { $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); $contentType = match ($extension) { 'jpg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'pdf' => 'application/pdf', default => 'application/octet-stream', }; } $filename = basename($filePath); return response($response, 200) ->header('Content-Type', $contentType) ->header('Content-Disposition', "inline; filename=\"{$filename}\"") ->header('Content-Length', strlen($response)); } }