如何使用DataTable列中的可下载链接实现下载pdf / docx文件

时间:2018-05-10 09:09:05

标签: file download datatables django-rest-framework

我想从DataTable列下载文件,HTML代码如下:

$(document).ready(function() {
        var table = $('#sample').DataTable({
            "serverSide": true,
            "ajax": "/api/sample/?format=datatables",
            "columns": [
                {"data": "hospital_name"},
                {"data": "report_path", "render":function(data,type,row,meta){
                    return '<a href="{% url 'downloads' "'+data+'" %}">Download</a>'

下载总是失败。也许有问题: 返回'下载' 如何发送“report_path”视图功能下载并正确触发下载。

downloads in views.py:
def downloads(request, filename):
    file_pathname = filename
    with open(file_pathname, 'rb') as f:
        file = File(f)
        response = HttpResponse(file.chunks(),content_type='APPLICATION/OCTET-STREAM')
        response['Content-Disposition'] = 'attachment; filename=' + filename
        response['Content-Length'] = os.path.getsize(file_pathname)
    return response

urls.py:
urlpatterns = [
    url('^admin/', admin.site.urls),
    url('^api/', include(router.urls)),
    url('$', views.index,name='htdbs'),
    url('htdbs/', include('htdbs.urls')),
    url(r'^downloads/(?P<filename>.*)$', views.downloads, name='downloads')
]

我把上传的文件放在MEDIA_ROOT,seetings.py:

# media storage
MEDIA_ROOT = 'D:/uploads/'
MEDIA_URL = '/uploads/'

在models.py文件中:

report_path = models.FileField(upload_to=settings.MEDIA_ROOT+'/%Y/%m/%d')

那么,我怎样才能成功下载上传的pdf / docx文件?

0 个答案:

没有答案