0

我已经使用 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(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

感谢帮助

4

1 回答 1

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
于 2019-01-04T07:11:39.433 回答