Created
March 29, 2024 23:53
-
-
Save arashatt/9d1f79a5d8cf4cfe0a0374f9be84fca1 to your computer and use it in GitHub Desktop.
upload server (python - flask - code ) it should have index.html in the same directory to POST files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from flask import Flask, request, jsonify, make_response, send_from_directory | |
| from werkzeug.utils import secure_filename | |
| import os | |
| import secrets # For secure random filename generation | |
| app = Flask(__name__) | |
| UPLOAD_FOLDER = "uploads" # Change this to your desired upload folder | |
| ALLOWED_EXTENSIONS = set(['mkv', 'txt', 'pdf', 'jpg', 'png']) # Allowed file extensions | |
| def allowed_file(filename): | |
| """Checks if the filename extension is allowed.""" | |
| return '.' in filename and \ | |
| filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | |
| @app.route('/', methods=['GET']) | |
| def index(): | |
| """Serves the basic HTML form for file upload.""" | |
| return send_from_directory('.', 'index.html') # Assuming index.html exists | |
| @app.route('/upload', methods=['POST']) | |
| def upload_file(): | |
| """Handles file upload requests.""" | |
| if 'file' not in request.files: | |
| print(request.files) | |
| return jsonify({'error': 'No file part in the request'}), 400 | |
| file = request.files['file'] | |
| if file.filename == '': | |
| print("empty filename") | |
| return jsonify({'error': 'No selected file'}), 400 | |
| if file and allowed_file(file.filename): | |
| print("file type is allowed") | |
| filename = secure_filename(file.filename) | |
| # Generate a secure random filename to avoid conflicts and bypass potential vulnerabilities | |
| random_filename = secrets.token_hex(16) + os.path.splitext(filename)[1].lower() | |
| filepath = os.path.join(UPLOAD_FOLDER, random_filename) | |
| # Check if upload folder exists, create it if not | |
| if not os.path.exists(UPLOAD_FOLDER): | |
| os.makedirs(UPLOAD_FOLDER) | |
| try: | |
| file.save(filepath) | |
| return jsonify({'message': 'File uploaded successfully'}), 201 | |
| except Exception as e: | |
| return jsonify({'error': f'Upload failed: {e}'}), 500 | |
| return jsonify({'error': 'Forbidden file type'}), 403 | |
| if __name__ == '__main__': | |
| app.run(debug=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>File Upload</title> | |
| </head> | |
| <body> | |
| <h1>Upload a File</h1> | |
| <form action="/upload" method="POST" enctype="multipart/form-data"> | |
| <label for="file">Select file:</label> | |
| <input type="file" id="file" name="file"> | |
| <br> | |
| <button type="submit">Upload</button> | |
| </form> | |
| <div id="message"></div> </body> | |
| <script> | |
| // Optional: Add JavaScript to handle form submission and display messages (if desired) | |
| document.getElementById('uploadForm').addEventListener('submit', function(e) { | |
| e.preventDefault(); // Prevent default form submission behavior | |
| const formData = new FormData(this); // Create FormData object from form data | |
| fetch('/upload', { // Send POST request with FormData | |
| method: 'POST', | |
| body: formData | |
| }) | |
| .then(response => response.json()) // Parse JSON response | |
| .then(data => { | |
| const messageElement = document.getElementById('message'); | |
| if (data.message) { | |
| messageElement.innerHTML = data.message; // Display success message | |
| } else if (data.error) { | |
| messageElement.innerHTML = data.error; // Display error message | |
| } | |
| }) | |
| .catch(error => { | |
| console.error(error); // Handle potential errors | |
| }); | |
| }); | |
| </script> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment