Как скачать pdf файл с python на локальную машину - PullRequest
0 голосов
/ 04 января 2019

Я создал веб-приложение, используя Django 1.11, мне нужно загружать файлы через FTP или HTTP в мою локальную систему из приложения (используя браузер), используя python.

HTML-код:

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

Код JavaScript:

<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:

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

Просмотров:

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

Спасибо за помощь

Ответы [ 2 ]

0 голосов
/ 04 января 2019

Вдохновленный @Exprator

import requests
from django.http.response import StreamingHttpResponse


def index(request):
    file_url = "http://codex.cs.yale.edu/avi/db-book/db4/slide-dir/ch1-2.pdf"
    r = requests.get(file_url, stream=True)
    response = StreamingHttpResponse(content_type='application/pdf', streaming_content=r.iter_content(chunk_size=1024))
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
    return response
0 голосов
/ 04 января 2019
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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...