Flask - 从主上传文件夹的子目录中获取文件

时间:2014-01-27 19:41:49

标签: python web flask

在我的应用上,我正在尝试返回之前由用户上传的文件。我有一个大的上传文件夹,有些文件在该文件夹的子文件夹中。我如何返回这些子目录中的文件?对于不在子文件夹中的文件,这可以正常工作:

@app.route ('/uploads/<filename>')
def uploaded_image(filename): 
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

然而,对于上传文件夹的子文件夹中的一个,我试过

@app.route('/uploads/<new_folder_name>/<filename>')
def uploaded_file(filename, new_folder_name):
return send_from_directory(app.config['/UPLOAD_FOLDER/<new_folder_name>'], filename)

它不起作用。

1 个答案:

答案 0 :(得分:0)

您需要自己一起加入路径,但首先清理文件夹名称。拒绝其中包含路径分隔符的任何内容,例如:

@app.route('/uploads/<new_folder_name>/<filename>')
def uploaded_file(filename, new_folder_name):
    if '/' in filename or '\\' in filename:
        abort(404)
    return send_from_directory(
        os.join(app.config['UPLOAD_FOLDER'], new_folder_name), filename)

这会创建一个新路径,方法是使用app.config['UPLOAD_FOLDER']作为基目录,new_folder_name作为子文件夹,filename作为该子文件夹中的文件。

更好的是,werkzeug库(Flask的基础)附带了一个处理所有不安全边框的专用函数werkzeug.security.safe_join()

from werkzeug.security import safe_join

@app.route('/uploads/<new_folder_name>/<filename>')
def uploaded_file(filename, new_folder_name):
    path = safe_join(os.join(app.config['UPLOAD_FOLDER'], new_folder_name)
    if path is None:
        abort(404)
    return send_from_directory(path, filename)

如果您想从目录中取filename,请使用:

from werkzeug.security import safe_join

@app.route('/uploads/<new_folder_name>/<filename>')
def uploaded_file(filename, new_folder_name):
    path = safe_join(os.join(app.config['UPLOAD_FOLDER'], new_folder_name)
    if path is None:
        abort(404)
    files = os.listdir(path)
    if not files:
        abort(404)
    return send_from_directory(path, files[0])