到目前为止,我正在尝试使用 Django 提供一个简单的文本文件,但没有成功。我认为我的 Django 代码没问题:
def status(request):
# Get data from database
parameters = get_parameters_from_database()
if request.method == "GET":
// Stuff here to render the view for a GET request
return render_to_response('myapp/status.html', {'page_name': 'status', 'parameters' : parameters})
elif request.method == "POST":
if request.POST['request_name'] == 'download_txt':
file_path = parameters['file_path']
with open(file_path, 'rb') as fsock:
response = HttpResponse()
response['content_type'] = 'text/plain'
response['Content-Disposition'] = 'attachment; filename=current.txt'
response.write(fsock.read())
print(response)
return response
当收到 POST 请求时,它会在网络服务器控制台中打印以下内容,所以我认为没问题:
<HttpResponse status_code=200, "text/html; charset=utf-8">
所以我认为问题是我没有在 Jquery 的 Ajax 方法中处理成功事件:
$('#downloadButton').click(function(){
$.ajax({
url: '',
method: 'POST',
data: {
request_name: 'download_txt'
},
success: function (data) {
//TODO
},
error: function (err) {
console.log('Error downloading file');
}
});
});
问题是我不知道应该如何处理成功事件:我认为一旦服务器用 content_type
应答,浏览器就会自动下载文件
有什么帮助吗?
最佳答案
没有 ajax 只需返回带有文件附件的 httpresponse
from django.http import HttpResponse
def my_view(request):
# some code
file_data = "some text"
response = HttpResponse(file_data, content_type='application/text charset=utf-8')
response['Content-Disposition'] = 'attachment; filename="foo.txt"'
return response
关于jquery - 在 Django 中下载简单的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49770572/