Python文件上传异常排查(动态Session ID文件夹未接收文件)及Base64编码文件解析处理求助
Hey there! Let's tackle your two issues one by one—first the file upload folder misplacement problem, then the base64 decoding task.
If your uploaded files aren't landing in the dynamically generated session-specific folder, here are the most common fixes to check:
Ensure you're correctly retrieving the Session ID
Double-check that you're pulling the valid session ID for the current user. For example, in Flask this would besession.sid, and in Django it'srequest.session.session_key. If the session ID is missing or uninitialized, your folder path will be incorrect.Verify folder creation logic
Make sure you're creating the session folder before saving the file, and handle cases where the folder might already exist. Useos.makedirs()withexist_ok=Trueto avoid errors:import os from flask import session # Adjust based on your framework session_id = session.sid upload_folder = os.path.join("uploads", session_id) # Create folder (no error if it already exists) os.makedirs(upload_folder, exist_ok=True)Confirm the file save path uses the dynamic folder
Don't hardcode the upload path! Ensure your file handler uses the session-specific folder when saving:from flask import request uploaded_file = request.files["file"] # Build the full path with the session folder save_path = os.path.join(upload_folder, uploaded_file.filename) uploaded_file.save(save_path)Debug the actual save path
Add a print statement to log where files are being saved:print(f"Attempting to save file to: {save_path}")This will quickly tell you if the path matches your expected session folder.
Here's a step-by-step breakdown to extract and decode the base64 file data from your JSON structure:
Load the JSON data
First, parse your JSON into a Python dictionary (this could come from a request body, file, etc.):import json import base64 # Example JSON input (replace with your actual data source) json_input = '{"messageobj": {"fileData": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD..........."}}' data_dict = json.loads(json_input)Extract the base64 string and strip the data URI prefix
ThefileDatastring includes adata:image/jpeg;base64,prefix—you need to remove this to decode properly:file_data_str = data_dict["messageobj"]["fileData"] # Split off the prefix to get pure base64 content base64_content = file_data_str.split(",")[1]Decode and save the file
Usebase64.b64decode()to convert the string to bytes, then write it to a file (you can use your session-specific folder here too):decoded_file_bytes = base64.b64decode(base64_content) # Save to the session folder (reuse upload_folder from earlier) with open(os.path.join(upload_folder, "decoded_image.jpg"), "wb") as output_file: output_file.write(decoded_file_bytes)Handle dynamic file types
If you need to support multiple file types, extract the MIME type from the data URI to set the correct file extension:# Extract MIME type (e.g., "image/jpeg") mime_type = file_data_str.split(";")[0].split(":")[1] # Get the file extension (e.g., "jpeg") file_extension = mime_type.split("/")[1] # Save with the correct extension with open(os.path.join(upload_folder, f"decoded_file.{file_extension}"), "wb") as output_file: output_file.write(decoded_file_bytes)
内容的提问来源于stack exchange,提问作者Charlie

