python - 烧瓶 request.files 返回 ImmutableMultiDict([])
问题描述
我已经尝试了一百万次来让这个工作。我正在制作一个网络应用程序,并且我有一个按钮(模态)弹出,用户输入名称并上传文件。当用户点击 Save Well 时。request.files 返回 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代码如下所示:
@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')])])
只想添加以下代码有效。但是我怎样才能让它在我更大的网络应用程序上工作呢?我想这与app.route有关。但是我尝试了很多东西,比如使用 url_for 将其添加到操作表单中。似乎没有任何效果。
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 Request 预计会返回一个 ImmutableMultiDict:
包含所有上传文件的 MultiDict 对象。文件中的每个键都是
<input type="file" name="">
. files 中的每个值都是 Werkzeug FileStorage 对象。它的行为基本上类似于你从 Python 中知道的标准文件对象,不同之处在于它还有一个
save()
可以将文件存储在文件系统上的函数。
POST
请注意,仅当请求方法是,PUT
或者发布到 请求PATCH
的方法是时,文件才会包含数据。否则它将为空。<form>
enctype="multipart/form-data"
有关使用的数据结构的更多详细信息,请参阅 MultiDict / FileStorage 文档。
推荐阅读
- android - Mockito:验证 Mocked 方法不起作用
- python-3.x - 通过 API 从 Jira 获取自定义字段选项列表
- c# - 以另一种形式存储数据保护问题
- haskell - Data.Text 的一元折叠
- sql-server - sql server错误中的aioodbc问号
- excel - Excel - 下标超出范围
- javascript - 使用 vis.js 的时间轴组中所有项目的高度相同
- java - maven 属性不会被 -dParam.version 覆盖
- rest - Apache Camel - 作为 GET 请求的结果从 FTP 获取文件列表
- word2vec - 如何从 FastText 的输出矩阵中获取向量?