Handle file uploads, save them, and associate with the session.
(self, session_id: str)
| 656 | self.send_json_response({'error': str(e)}, status_code=500) |
| 657 | |
| 658 | def handle_file_upload(self, session_id: str): |
| 659 | """Handle file uploads, save them, and associate with the session.""" |
| 660 | form = cgi.FieldStorage( |
| 661 | fp=self.rfile, |
| 662 | headers=self.headers, |
| 663 | environ={'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type']} |
| 664 | ) |
| 665 | |
| 666 | uploaded_files = [] |
| 667 | if 'files' in form: |
| 668 | files = form['files'] |
| 669 | if not isinstance(files, list): |
| 670 | files = [files] |
| 671 | |
| 672 | upload_dir = "shared_uploads" |
| 673 | os.makedirs(upload_dir, exist_ok=True) |
| 674 | |
| 675 | for file_item in files: |
| 676 | if file_item.filename: |
| 677 | # Create a unique filename to avoid overwrites |
| 678 | unique_filename = f"{uuid.uuid4()}_{file_item.filename}" |
| 679 | file_path = os.path.join(upload_dir, unique_filename) |
| 680 | |
| 681 | with open(file_path, 'wb') as f: |
| 682 | f.write(file_item.file.read()) |
| 683 | |
| 684 | # Store the absolute path for the indexing service |
| 685 | absolute_file_path = os.path.abspath(file_path) |
| 686 | db.add_document_to_session(session_id, absolute_file_path) |
| 687 | uploaded_files.append({"filename": file_item.filename, "stored_path": absolute_file_path}) |
| 688 | |
| 689 | if not uploaded_files: |
| 690 | self.send_json_response({"error": "No files were uploaded"}, status_code=400) |
| 691 | return |
| 692 | |
| 693 | self.send_json_response({ |
| 694 | "message": f"Successfully uploaded {len(uploaded_files)} files.", |
| 695 | "uploaded_files": uploaded_files |
| 696 | }) |
| 697 | |
| 698 | def handle_index_documents(self, session_id: str): |
| 699 | """Triggers indexing for all documents in a session.""" |
no test coverage detected