flask实现个人文件管理系统,实现文件的上传,下载,分类,用户登录注册等功能完整代码实现
时间: 2024-05-08 12:18:49 浏览: 242
python3 flask实现文件上传功能
好的,下面是使用 Flask 实现个人文件管理系统的示例代码:
```
from flask import Flask, render_template, request, redirect, url_for, session, flash
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
app.secret_key = 'your_secret_key'
app.config['UPLOAD_FOLDER'] = '/path/to/upload/folder'
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
@app.route('/')
def index():
if 'username' in session:
return render_template('index.html', username=session['username'])
else:
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# 在此处验证用户输入的用户名和密码是否正确,正确的话将其保存到 session 中
session['username'] = username
flash('You were logged in')
return redirect(url_for('index'))
else:
return render_template('login.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# 在此处将用户提交的用户名和密码保存到数据库中
flash('You were registered')
return redirect(url_for('login'))
else:
return render_template('register.html')
@app.route('/logout')
def logout():
session.pop('username', None)
flash('You were logged out')
return redirect(url_for('index'))
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
flash('File uploaded successfully')
return redirect(url_for('index'))
else:
flash('Invalid file type')
return redirect(url_for('upload'))
else:
return render_template('upload.html')
@app.route('/download/<filename>')
def download(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run()
```
在这个示例中,我们实现了文件的上传、下载、和分类等功能,同时还实现了用户的登录和注册功能。在登录后,用户可以上传文件,并将其保存到服务器上的指定路径下。在下载文件时,用户可以通过文件名获取文件,并将文件下载到本地计算机中。
阅读全文