Flask实现远程上传下载音频| 青训营

516 阅读2分钟

服务器端:

from flask import Flask, request, send_file
from werkzeug.utils import secure_filename
import os
import time
from flask_cors import CORS


app = Flask(__name__)
CORS(app)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'wav'}
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return 'No file part'

    file = request.files['file']

    if file.filename == '':
        return 'No selected file'

    if not allowed_file(file.filename):
        return 'Invalid file type'

    filename = secure_filename(file.filename)
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

    time.sleep(5)

    return send_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), as_attachment=True)


if __name__ == '__main__':
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    app.run(debug=True, port=5000, host='0.0.0.0')

以下为代码的一些要点:

  1. secure_filenameWerkzeug库中的一个函数,它用于安全地生成一个文件名,比如test 1.txt-->test_1.txt。

  2. CORS跨域操作。

  3. app.config['UPLOAD_FOLDER'] = 'uploads':设置了上传文件的保存目录为'uploads'文件夹。

  4. app.config['ALLOWED_EXTENSIONS'] = {'wav'}:设置了允许上传的文件扩展名为wav

  5. app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024:设置了上传文件的最大大小为16MB。超过这个大小的文件将会被拒绝上传。

  6. 函数allowed_file,用于检查一个文件名是否符合允许上传的文件扩展名。

  7. request.files是一个字典,其中包含了请求中所有的文件对象

  8. if file.filename == ''::检查文件名是否为空。如果文件名为空,则返回一个提示信息'No selected file',表示没有选择文件。

  9. file.save:将上传的文件保存到指定的目录中。

  10. send_file:发送指定路径下的文件给客户端进行下载。其中:

    • os.path.join(app.config['UPLOAD_FOLDER'], filename)用于拼接文件的完整路径,指定要发送的文件。
    • as_attachment=True表示以附件形式发送文件,客户端会弹出文件下载对话框,让用户选择保存文件的位置。
  11. app.run(debug=True, port=5000, host='0.0.0.0'):这行代码启动 Flask 应用,并配置了一些参数。其中:

    • host='0.0.0.0':设置应用的监听地址为 0.0.0.0。这样配置后,应用将会监听所有可用的网络接口,而不仅仅是本地回环接口 (localhost 或 127.0.0.1)。
    • debug=True:设置调试模式为开启。在调试模式下,应用会自动重新加载修改过的代码,并显示详细的错误信息。这对于开发和调试应用非常有用,但在生产环境中不应开启调试模式。
    • port=5000:设置应用运行的端口号为 5000。可以根据需要修改端口号。

客户端:

import requests

url = "http://localhost:5000/upload"  # 服务器端的地址

file_path = "你的音频文件.wav"
files = {'file': open(file_path, 'rb')}

response = requests.post(url, files=files)

output_file_path = "output.wav"
with open(output_file_path, 'wb') as f:
    f.write(response.content)

print("音频文件保存成功:", output_file_path)