How to handle the return of files (PDF) in an AJAX call?

Asked

Viewed 143 times

0

I made a code that selects the documents that are in a bank FTP and by clicking download it runs a AJAX call to the DJANGO where I call the FTP again, download the file and send back to the AJAX. But I can’t find how to handle the file .PDF.

inserir a descrição da imagem aqui

I haven’t figured out why AJAX are treating as error and not as sucess. I should be defining the dataType differently? Or by treating rest in Django?

What I want to do is, select the file the user wants to download, pull it on ftp and download on the user’s machine.

Follows the codes:

AJAX:

    $.ajax({
        url:"{% url 'action_documents' %}",
        async: false,
        dataType: 'json',
        type: 'GET',
        data: {
            'documentos[]': documentos,
            'action': action,
    },
        success: function (data) {
            console.log('Sucess', data);
            result = 'S U C E S S O';
            // Tentando inserir o pdf em algum lugar para confimar que ele está -
            // chegando no Front End
            let html = ajax.decode(data.responseText).html;
            $('#main1').append(html);
            //ajax.get('pageContent').update(html);
        },
        error: function (response) {
            # o Ajax está saindo aqui
            console.log('Erro nos Documentos --> ', response);
            result = 'E R R O';
        }
    });

DJANGO:

if request.is_ajax:
    documentos = request.GET.get('documentos[]')
    # name é meramente ilustrativo
    name = documentos[1]
    ftp = logar_ftp()
    try:
        buffer = io.BytesIO()
        ftp.retrbinary('RETR ' + name, buffer.write)
        buffer.seek(0)
        # sending response
        response = HttpResponse(buffer, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="' + name + '"'
    except IOError:
        # handle file not exist case here
        response = HttpResponseNotFound('<h1>File not exist</h1>')
else:
    response = HttpResponseNotFound('<h1>Request Ajax Error</h1>')
return response
  • How should I effect request download on user’s machine?!

1 answer

0

Ajax is a way to get data from a server without the need to reload the page, but it expects to receive a JSON with data from the server. You can save the file to your server and send as a response to Ajax a JSON object with the link to download, and in Success Voce USA window.location = data.url.

However your server may get very crowded with files, you can schedule a task on your server to clear the particular folder and delete the files from the previous day.

  • 1

    Or, consider the option to do the request without Ajax, using a standard get.

  • Yes, but in the case the data is in an FTP and there is no possibility to put them in the bank because it would need to change the whole structure of the same. I read in several places that you don’t put business rules in the front end (and they gave me tips about that too), so I always use Ajax to take Django and treat the rules there. That’s why I’m trying to send the file via ajax since it will always be not heavy PDF files. And what would be this 'get standard'' that you commented?! Another detail, I tried to use via link but would need login and password among other details I want to avoid...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.