我使用 xlwt 和 StringIO 根据客户端给出的输入在服务器端生成了一个 excel 文件。现在我想将文件发送回客户端,以便他/她可以保存它(最好使用保存对话框)。
我正在尝试使用 send_file
来做到这一点,但由于我不太擅长 javascript/jquery/ajax,所以我实际上不知道如何在客户端处理这个问题。根据下面的代码(主要从 Flask 主页收集),你能给我一个如何到达那里的提示吗?
感谢您的帮助!
代码如下:
请注意:JS 代码是由按钮上的单击事件触发的。当将 json 从客户端传递到服务器并返回时它工作正常...
Python
import StringIO
import wordpuzzle # The code that creates the excel file
@app.route('/_create_wordsearch')
def create_wordsearch():
wordlist = json.loads(request.args.get('wordlist'))
# create a stringIO object
output = StringIO.StringIO()
# Instantiate the PuzzleGrid class
p = wordpuzzle.PuzzleGrid(wordlist)
# Create the Puzzle
p.main()
# Create the xls file in memory
p.output2excel(output)
# Set back to start
output.seek(0)
# send back to client
return send_file(output, mimetype='application/vnd.ms-excel')
JS
$(document).ready(function() {
$("#create_btn").bind('click', function(){
//Get all words from list
var list = [];
$("#wordlist option").each(function(){
list.push($(this).val());
});
$.getJSON($SCRIPT_ROOT + '/_create_wordsearch', {
wordlist: JSON.stringify(list)
}, function(data){
// What goes in here?
});
return false;
});
});
最佳答案
假设页面上有一个 div 用作目标:
<div id="exportdiv"></div>
将 $.getJSON 调用替换为如下代码:
var url = $SCRIPT_ROOT + '/_create_wordsearch';
// hide the div, write the form
$('#exportdiv').hide()
.html('<form id="exportform" action="' + url + '" target="_blank" method="get">'
+ '<textarea name="wordlist">' + JSON.stringify(list) +'</textarea>'
+ '</form>');
// submit the form
$('#exportform').submit();
在服务器端,您需要对 JSON 进行转义。我不确定你是否可以喂Markup.unescape()直接进入 json.loads 但它会是这样的:
wordlist = json.loads(Markup(request.args.get('wordlist')).unescape())
关于javascript - python flask : How to handle send_file on the client side,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23978927/