【发布时间】:2014-06-01 10:30:47
【问题描述】:
我使用 xlwt 和 StringIO 从客户端给出的输入原位生成了一个 excel 文件服务器端。现在我想将文件发送回客户端,以便他/她可以保存它(最好使用保存对话框)。
我正在尝试使用send_file 来做到这一点,但由于我对 javascript/jquery/ajax 不太擅长,我实际上不知道如何在客户端处理这个问题。根据下面的代码(主要来自烧瓶主页),你能告诉我如何到达那里吗?
感谢您的帮助!
代码如下:
请注意: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;
});
});
【问题讨论】:
-
我不相信您可以为此使用 JavaScript。您需要允许浏览器向
/_create_wordsearch提交表单(很可能是 POST),以便处理文件下载。 -
@dirn: 总是很遗憾听到一个人的努力方向错误并且一无所获;)...好吧 :(,我猜。我将如何使用 POST 来做到这一点?你能链接到一个好的代码示例?
-
你只需要一个 HTML
form。 -
@dirn:你有使用flask和html的好代码示例吗?我是新手,我无法区分好坏。我对python很好。 html/js/css webthingy 没那么多。我只找到 python/flask 方面(教程等),但从来没有真正的完整示例,包括 html 甚至 js。
-
你的 HTML 是什么样的?我想你的工作大部分已经完成了。您只需要更新您的视图以接受 POST。 quickstart 有一个关于 HTTP 方法的部分。
标签: javascript jquery python flask savefiledialog