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.
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?!
Or, consider the option to do the request without Ajax, using a standard get.
– Robson Silva
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...
– Nicolas