File download with nginx, django

1.4k views Asked by At

I'm currently writing a small personal-use website served with nginx, utilizing uwsgi, django, and bootstrap. All is going smoothly except for one issue that I cannot figure out. I have download links (buttons) on the site, and when clicked, should initiate a file download. Here is the view that is executed when a button is pressed:

@login_required
def download_file(request):
    '''
    downloads a file given a specified UUID
    '''

    if request.method == 'GET':
        file_uuid = request.GET['file_id']

        file_row = Files.objects.get(uuid=file_uuid)
        file_name = file_row.file_name

        response = HttpResponse()
        response['Content-Disposition'] = 'attachment; filename=%s' % file_name
        response['X-Accel-Redirect'] = '/media/files/%s' % file_name
        return response

    else:
        return redirect('/files')

/media/files is served directly by nginx as a internal location:

location /media/files/ {
   internal;
   alias /mnt/files/;
}

How this view is being called with an onclick event assigned to each button:

$('.download_btn').on('click',function(){
    download_file(this.id);
})

function download_file(uuid){
    $('.file_id').val(uuid);
    $('.get_file').submit();
}

I have a form with a single hidden field. This gets set to the id (uuid) of the button that is pressed.

Pretty simple right? My issue is that when the download button is pressed, the download is not initiated correctly. The user is not prompted with a save dialog, nor does the file begin automatically downloading (Chrome or Safari). Instead, in debug tools, I can see the file downloading to what seems to be local storage in the browser, or some memory location (these are large files; > 1GB). I see the memory ballooning, and eventually the browser will crash. Any clue what I'm doing wrong here? Based on what I've been reading, this should be working without issue.

0

There are 0 answers