Flask文件上传路径异常求助:无法正确识别用户本地文件路径
Fixing Flask File Upload Path Issues
Hey there! Let's break down what's causing those path errors in your Flask file upload feature and get it working properly.
What's Going Wrong
Your core issue comes from misunderstanding how Flask handles uploaded files:
- When a user uploads a file from their local machine (Windows or Kali), the client-side file path doesn't exist on your Flask server. The
filenameattribute of the uploaded file object only gives you the name of the file, not its full path on the user's computer. - When you use
open(filename, 'rb'), your server is trying to look for that file in its own current working directory (which is why it's searching/home/kali/Downloads/instead of the user's actual path). - Using
os.chdir()also introduces unnecessary complexity and potential bugs with file paths.
Corrected Code
Here's your code with fixes applied, with comments pointing out key changes:
from flask import Flask, render_template, request, redirect, send_file, flash import os import shutil from flaskmalwarecheck import malwaresignature from flaskmalwarecheck import formattedpdf from flaskmalwarecheck import entropy import argparse from elastic import elasticupload filetypes = [b'MZ'] app= Flask(__name__) # Add a secret key for flash messages (required for user feedback) app.secret_key = 'your-custom-secret-key-here' # Define upload folder as a config variable for cleaner code UPLOAD_FOLDER = "/home/kali/Downloads/webserverup/" app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER # Optional: Set maximum upload file size (e.g., 16MB to prevent large file crashes) app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # Ensure upload folder exists (create it if missing) os.makedirs(UPLOAD_FOLDER, exist_ok=True) @app.route('/') def main(): return render_template('attempt.html') @app.route('/upload', methods = ['GET', 'POST']) def upload(): if request.method == 'POST': n = request.files.get('file') # Check if user actually selected a file if not n or n.filename == '': flash('No file selected for upload') return redirect('/') filename = n.filename # Get the full absolute path to save the uploaded file save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) try: # Read the file header DIRECTLY from the uploaded file object (no local file needed) header = n.read(32) # Reset the file pointer since we read from it before saving n.seek(0) for call in filetypes: if call in header: # Save the uploaded file to the correct server path n.save(save_path) # Pass the FULL file path to your malware analysis functions malware_file, ISO8601, hashmethod, arch, importeddlls, imphash, fuzzyhash,warnings = malwaresignature(save_path) formattedpdf(save_path, malware_file, ISO8601, hashmethod, arch, importeddlls, imphash, fuzzyhash,warnings) elasticupload() # Clean up the uploaded file after processing os.remove(save_path) return redirect('/download', code=302) # If file type doesn't match your required header flash('Uploaded file is not a valid PE file') return redirect('/') except FileNotFoundError as e: flash(f'File processing error: {str(e)}') return redirect('/') except Exception as e: # Catch other unexpected errors for debugging flash(f'An unexpected issue occurred: {str(e)}') return redirect('/') else: return redirect('/') @app.route('/download') def download(): pdf_path = os.path.join(app.config['UPLOAD_FOLDER'], 'Sample.pdf') if os.path.exists(pdf_path): return send_file(pdf_path, as_attachment=True) else: flash('PDF report not found - did you upload a valid file first?') return redirect('/') @app.route('/transparent') def transparent(): with app.open_resource('flaskmalwarecheck.py', 'r') as e: contents = e.read() return contents parser = argparse.ArgumentParser() parser.add_argument("ip", help="Enter host IP", type=str) parser.add_argument("port", help="Port to be hosted on", type=int) args = parser.parse_args() if __name__ == "__main__": app.run(host=args.ip, port=args.port, ssl_context=('cert.pem', 'key.pem'))
Key Fixes & Recommendations
- Use the uploaded file object directly: Instead of trying to open the file via its client-side filename, read content straight from
n(the file object Flask provides for uploads). - Avoid
os.chdir(): Always use absolute file paths (likesave_path) to reference files instead of changing the server's working directory. - Add user feedback: Flash messages help you and your users understand exactly what went wrong (e.g., missing file, invalid type).
- Guarantee upload folder exists:
os.makedirs(UPLOAD_FOLDER, exist_ok=True)prevents path errors if the folder was deleted or never created. - Limit upload size: Prevent large files from crashing your server by setting
MAX_CONTENT_LENGTH. - Clean up safely: Reference files by their full path when deleting, to avoid accidentally removing the wrong files.
内容的提问来源于stack exchange,提问作者hashmaster
相关产品推荐
相关产品推荐

