0

I have created the web application using Django 1.11 , I need to download files over the FTP or HTTP to my local system from application (Using Browser) using python.

HTML Code:

.....
{% block content %}
{% csrf_token %}
<div>
  <button type="submit" onclick="download_payslip(10)">Download</button>
</div>
{% endblock content %}
.....

JavaScript Code:

<script type="text/javascript">
function download_payslip(emp_pay_id){
var dataString="&csrfmiddlewaretoken=" +$('input[name=csrfmiddlewaretoken]').val()
dataString+='&emp_pay_id='+emp_pay_id
$.ajax({
  type:'POST',
  url:'/payslipgen/render_pdf/',
  data:dataString,
  success:function(data){
      Console.log(data)
  },
  error: function (err) {
    alert("Error");
  },
})
}
</script>

URL code:

url(r'^payslipgen/render_pdf/$', views.download_payslip, name='DownloadPaySlip')

Views:

def download_payslip(request):
    file_path = "/home/ubuntu/hrmngmt/hrmngmt/static/myfile.pdf"
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/pdf")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404

Thanks for help

Manjunath Raddi
  • 421
  • 6
  • 15

1 Answers1

1
import os
from django.conf import settings
from django.http import HttpResponse

def download(request, path):
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/pdf")
            response['Content-Disposition'] = 'inline; filename='payslip.pdf'
            return response
    raise Http404
Exprator
  • 26,992
  • 6
  • 47
  • 59
  • Thanks, but it is downloading in server where my python code is running, I need to download to my local system. I have already PDF file in server where my application is running , that pdf file should download to my local system using application (Application is created using Django 1.11) – Manjunath Raddi Jan 04 '19 at 07:28
  • storing file on server may cause storage problem :( – JPG Jan 04 '19 at 07:47
  • I have edit my question, after response from sever , i can see the response data in console , but I don;t know how to convert to pdf, could you please help me – Manjunath Raddi Jan 04 '19 at 08:11
  • @Exprator , It's not working, in server I am getting response 'HTTP/1.1" 200' but , when it reach to javascript, in ajax function any code need to add. – Manjunath Raddi Jan 04 '19 at 09:31
  • go through this link, you will understand https://stackoverflow.com/questions/20830309/download-file-using-an-ajax-request – Exprator Jan 04 '19 at 09:34
  • @Exprator still not working , , any other way to do this using django application – Manjunath Raddi Jan 04 '19 at 10:29