Creating a django file for upload using javascript / jQuery

Using Django, I want to make some data available for download.

My jQuery call looks like this:

$.getJSON("/get_data", 
            { users: users, study: "{{study.id}}" } ,
            function(json){
                alert('some data!');
            }
);

This calls up one of my Django views, which in turn generates some JSON and tries to make this JSON text in the file to load

jsonResponse = json.dumps(data, cls=DjangoJSONEncoder)

jsonFile = cStringIO.StringIO()
jsonFile.write(jsonResponse)

response = HttpResponse(jsonFile, mimetype='application/json')
response['Content-Disposition'] = 'attachment; filename=data.txt'

return response

However, this does not work. Looking around for a while, I think I need to change something from both ends - Javascript and python / Django code, but I don’t quite understand what exactly.

For Python, my main concern is to use cStringIO (especially the fact that I cannot close jsonFile before returning without asking for a ValueError: I / O operation in the closed file).

, FileWrapper ( post), .

Javascript , .

!

+5
1

iframe.

urls.py

url(r'^test/getFile', 'getFile')

views.py

def getFile(request):
    fileContent = "Your name is %s" % request.GET['name']
    res = HttpResponse(fileContent)
    res['Content-Disposition'] = 'attachment; filename=yourname.txt'
    return res

<script type="text/javascript">
    var data = {name: 'Jon'};
    $(function(){
        $("body").append('<iframe src="/test/getFile?'+ $.param(data) + '" style="display: none;" ></iframe>');
    });
</script>
+7

All Articles