3

我有以下文件结构:

.
├── app
│   ├── api_routes
│   │   ├── forms.py
│   │   ├── __init__.py
│   │   └── routes.py
│   ├── __init__.py
│   ├── main_routes
│   │   ├── forms.py
│   │   ├── __init__.py
│   │   └── routes.py
│   ├── models.py
│   ├── static
│   │   └── styles.css
│   ├── templates
│   │   └── base.html
│   └── uploads
│       └── 10_0_0.jpg
├── application.py
└── config.py

在我的 config.py 我有这个:

class Config(object):
    UPLOAD_FOLDER = 'uploads/'

当我保存上传的文件,然后将其发送回用户(仅作为示例)时,我正在使用:

fname = 'foo.jpg'
fname_save = os.path.join(current_app.root_path, current_app.config['UPLOAD_FOLDER'], fname)
fname_retr = os.path.join(current_app.config['UPLOAD_FOLDER'], fname)
file.save(fname_save)
return send_from_directory(os.path.dirname(fname_retr),
                           os.path.basename(fname_retr))

cwd 中的上传文件夹(保存文件的位置)和烧瓶模块正在运行的文件夹(app/)具有不同的名称,有点乏味。有没有比我目前更优雅的解决方案来解决这个问题?

4

1 回答 1

2

我会这样做:

@app.route('/upload', methods=['POST'])
def myroute():
    fname = 'foo.jpg'
    file = request.file[0] # not save at all
    send_back_file = io.BytesIO(file.read())
    file.seek(0)
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], fname))
    return send_file(send_back_file, attachment_filename=fname, as_attachement=True)

资源:

于 2018-08-01T09:22:31.303 回答