from flask import Flask, request, redirect, url_for, send_from_directory, render_template_string
import os
app = Flask(__name__)
app.config['upload'] = 'uploads' # 上传文件保存的目录
os.makedirs(app.config['upload'], exist_ok=True)
@app.route('/')
def upload_form():
return '''
<html>
<body>
<h1>Upload Files</h1>
<form method='post' enctype='multipart/form-data'>
<input type='file' name='files' multiple>
<input type='submit' value='Upload'>
</form>
<hr>
<h1>Download Files</h1>
<form method='get' action='/download'>
<input type='submit' value='List Files'>
</form>
</body>
</html>
'''
@app.route('/', methods=['POST'])
def upload_file():
if 'files' not in request.files:
return redirect(request.url)
files = request.files.getlist('files')
if not files or all(file.filename == '' for file in files):
return redirect(request.url)
uploaded_files = []
for file in files:
if file.filename != '':
file.save(os.path.join(app.config['upload'], file.filename))
uploaded_files.append(file.filename)
return f'Files {",".join(uploaded_files)} uploaded successfully!'
@app.route('/download', methods=['GET'])
def download_form():
# 列出 uploads 目录中的所有文件
files = os.listdir(app.config['upload'])
# 创建一个表单来选择要下载的文件
return render_template_string('''
<html>
<body>
<h1>Select a File to Download</h1>
{% for file in files %}
<a href='{{ url_for('download_file', filename=file) }}'>{{ file }}</a><br>
{% endfor %}
<a href='/'>Back to Upload</a>
</body>
</html>
''', files=files)
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
# 确保请求的文件存在于 uploads 目录中
return send_from_directory(app.config['upload'], filename, as_attachment=True)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=50504) # 在所有可用接口上运行应用
内网文件传输
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 大家好,今天我要给大家分享一个我最近发现的宝贝——LocalSend v1.15.0,一款免费的跨平台局域网文件传...
- 1.IO是什么? ⦁定义 在内存中存在数据交换的操作和终端交互:input, output和磁盘交互:read, ...