单击使用flask提交后,如何将文件保存在其他目录中?

时间:2018-06-20 15:35:52

标签: python-3.x file-upload flask

我有一个简单的python文件,该文件从本地目录发送文件以html显示。而且,当用户单击“提交”时,我想将此文件保存到其他目录,但似乎无法实现。 这是我的代码:

Uploader.py

from __future__ import print_function
from random import choice
from flask import Flask, request, redirect, url_for, flash, render_template, abort, send_file, session
from werkzeug.utils import secure_filename
from flask import send_from_directory
import sys, os

app = Flask(__name__)
@app.route('/')
def init(file_Idx=0):
    files = os.listdir(DOWNLOAD_FOLDER)
    filePath = os.path.join(DOWNLOAD_FOLDER, files[file_Idx])
    return render_template('files.html', file=filePath)

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['image'] #Failing here!!!
    f = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
    file.save(f)
    return render_template('files.html')

files.html

<form action="/upload" method="post" enctype="multipart/form-data">
        <img src="{{file}}"/>                
        <input type=submit name="image">
</form>

现在正在显示图像,但是我似乎无法将文件传递给upload_file()来将其保存在upload_folder中。我该如何工作?

1 个答案:

答案 0 :(得分:0)

尝试此操作,您可以在其中定义所需的路径。 您可以修改行

file.save(os.path.join("/tmp/", filename))

并在其中放置所需的路径。

from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)

@app.route('/upload')
def upload_file():
    return render_template('upload.html')

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
    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("/tmp/", filename))

if __name__ == '__main__':
    app.run(debug = True)

和相应的HTML代码

<form id="package_form" action="" method="POST">
<div>
   <p>Upload Packages:</p>
   <p><input id="upload_button" type="file" class="btn btn-default btn-xs" name="file"></p>
   <p><input id="submit_button" type="submit" class="btn btn-success" value="Upload">
</div>