如何使用python将pdf文件下载到本地计算机

时间:2019-01-04 07:06:29

标签: django python-2.7 ftp

我已经使用Django 1.11创建了Web应用程序,我需要使用python通过FTP或HTTP从应用程序(使用浏览器)将文件下载到本地系统。

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 :(得分: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

答案 1 :(得分:0)

@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