烧瓶request.files返回ImmutableMultiDict([]) [英] Flask request.files returns ImmutableMultiDict([])
问题描述
我已经尝试了100万次才能使其正常工作.我正在制作一个Web应用程序,并且有一个按钮(模式),当用户输入名称并上传文件时,该按钮会弹出.当用户单击保存良好"时.request.files返回ImmutableMultiDict([])
I have tried a million times to get this working. I am making a web app and I have a button (modal) that pops up where the user enters the name and uploads a file. When the user clicks on Save Well. The request.files returns ImmutableMultiDict([])
这是按钮:
网页上的模式代码:
$(document).ready(function(){
$('#SaveNewWellButton').on('click', function(e){
e.preventDefault()
$.ajax({
url:'./createNewWellfolder',
type:'post',
data:{'newWellNameImported':$("#newWellNameImported").val(),
'WTTcsvfile':$("#WTTcsvfile").val()
},
success: function(data){
//$("#result").text(data.result)
$('#selectWell').html(data)
alert( "New well created" );
},
error: function(error){
console.log(error);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="table-add float-right mb-3 mr-2" data-toggle="modal" data-target="#myModal">
<button type="submit" class="btn btn-success">Add New Well</button></span>
<!-- The Modal -->
<div class="modal fade" id="myModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Import CSV file:</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<form action="/createNewWellfolder" method="post" enctype="multipart/form-data">
<div class="modal-body">
Name of well:<input type="text" id="newWellNameImported" class="form-control"></input>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<input type="file" name="csvfile" value ="csvfile" id="csvfile">
</br>
<button type="submit" class="btn btn-primary" id="SaveNewWellButton">Save Well</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
python代码如下:
The python code looks like this:
@app.route('/createNewWellfolder', methods=['GET', 'POST'])
def createNewWellfolder():
print('request.method : %s', request.method)
print('request.files : %s', request.files)
print('request.args : %s', request.args)
print('request.form : %s', request.form)
print('request.values : %s', request.values)
终端的输出:
request.method : %s POST
request.files : %s ImmutableMultiDict([])
request.args : %s ImmutableMultiDict([])
request.form : %s ImmutableMultiDict([('newWellNameImported', 'Sample Well 14')])
request.values : %s CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([('newWellNameImported', 'Sample Well 14')])])
只需添加以下代码即可.但是,如何在大型Web应用程序上使用它呢?我想这与app.route有关.但是我已经尝试了很多事情,例如使用url_for等将其添加到动作表单中.似乎没有任何效果.
Just want to add that the below code works. But how can I get it to work on my larger web app? I guess it has something to do with app.route. But I have tried so many things, like adding it to the action form with url_for etc. Nothing seems to work.
import os
from flask import Flask, flash, send_from_directory, request, redirect, url_for
from werkzeug.utils import secure_filename
from os.path import dirname, join
DATA_DIR = join(dirname(__file__), 'data/')
wellNames = next(os.walk('data'))[1]
print(DATA_DIR, wellNames[0])
UPLOAD_FOLDER = DATA_DIR + wellNames[0] + '/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'csv', 'docx'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def createNewWellfolder():
if request.method == 'POST':
print('------------->', request.files)
# check if the post request has the file part
if 'csvfile' not in request.files:
flash('No file part')
file = request.files['csvfile']
print('------------->', file)
if file.filename == '':
flash('No selected file')
if file and allowed_file(file.filename):
print('hello im here------------->', file)
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return '''
<!-- Modal body -->
<form method=post enctype=multipart/form-data>
<div class="modal-body">
Name of well:<input type="text" id="newWellNameImported" class="form-control"></input>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<input type=file name="csvfile" id="csvfile" >
</br>
<button type="submit" class="btn btn-primary" id="SaveNewWellButton" >Save Well</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
'''
if __name__ == '__main__':
print('Opening single process Flask app with embedded Bokeh application on http://localhost:8000/')
app.secret_key = 'secret key'
app.debug = True
app.run(port = 8000)
终端的输出:
-------------> ImmutableMultiDict([('csvfile', <FileStorage: 'testcsv.csv' ('application/vnd.ms-excel')>)])
-------------> <FileStorage: 'testcsv.csv' ('application/vnd.ms-excel')>
hello im here-------------> <FileStorage: 'testcsv.csv' ('application/vnd.ms-excel')>
推荐答案
您介意对此问题进行详细说明吗?预计Flask请求会返回ImmutableMultiDict:
Would you mind elaborating on the issue a bit more? It's expected that Flask Request returns an ImmutableMultiDict:
包含所有上载文件的MultiDict对象.文件中的每个键是
< input type ="file" name =">
中的名称.文件中的每个值是一个Werkzeug FileStorage对象.
MultiDict object containing all uploaded files. Each key in files is the name from the
<input type="file" name="">
. Each value in files is a Werkzeug FileStorage object.
它的行为基本上就像您从Python知道的标准文件对象一样,区别在于它还具有可以存储的 save()
函数文件系统上的文件.
It basically behaves like a standard file object you know from Python,
with the difference that it also has a save()
function that can store
the file on the filesystem.
请注意,如果请求方法为 POST
,则文件将仅包含数据,发布到请求中的 PUT
或 PATCH
和< form>
enctype ="multipart/form-data"
.否则它将为空.
Note that files will only contain data if the request method was POST
,
PUT
or PATCH
and the <form>
that posted to the request had
enctype="multipart/form-data"
. It will be empty otherwise.
有关更多详细信息,请参见MultiDict/FileStorage文档.使用的数据结构.
See the MultiDict / FileStorage documentation for more details about the used data structure.
http://flask.pocoo.org/docs/1.0/api/#flask.Request.files
这篇关于烧瓶request.files返回ImmutableMultiDict([])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!