abhicodes's picture
Upload 6 files
2ace788 verified
raw
history blame
2.61 kB
from flask import Flask, request, redirect, url_for, send_file, render_template, flash
from flask_cors import CORS
from werkzeug.utils import secure_filename
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
import urllib.parse
import os
import io
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
CORS(app,resources={r"/*":{"origins":"*"}})
username = urllib.parse.quote_plus(os.getenv('MONGO_USERNAME'))
password = urllib.parse.quote_plus(os.getenv('MONGO_PASSWORD'))
restUri = os.getenv('REST_URI')
uri = f'mongodb+srv://{username}:{password}{restUri}'
client = MongoClient(uri, server_api=ServerApi('1'))
db = client['file_storage']
files_collection = db['files']
def allowed_file(filename):
return True
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
files = request.files.getlist('file')
for file in files:
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file_data = {
'filename': filename,
'data': file.read()
}
files_collection.insert_one(file_data)
flash('Files successfully uploaded')
return redirect(url_for('list_files'))
return render_template('upload.html')
@app.route('/uploads/<filename>')
def uploaded_file(filename):
file_data = files_collection.find_one({'filename': filename})
if file_data:
return send_file(
io.BytesIO(file_data['data']),
mimetype='application/octet-stream'
)
else:
return 'File not found'
@app.route('/files')
def list_files():
files = [file_data['filename'] for file_data in files_collection.find({}, {'_id': 1, 'filename': 1})]
return render_template('files.html', files=files)
@app.route('/delete/<filename>', methods=['POST'])
def delete_file(filename):
file_data = files_collection.find_one({'filename': filename})
if file_data:
files_collection.delete_one({'filename': filename})
flash('File successfully deleted')
else:
flash('File not found')
return redirect(url_for('list_files'))
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')