美文网首页我爱编程
2018-08-09Django 根据页面传递参数 下载文件

2018-08-09Django 根据页面传递参数 下载文件

作者: luke_skywalker | 来源:发表于2018-08-09 15:50 被阅读0次

    url设置

    
    url(r'^download/(?P\d+)/$',views.download,name='download'),
    
    

    view的download

    
    def download(request,id):
        if request:
            # print('request:',id)
            filePath = Model.objects.get(rprs_id__exact=id).rprs_file_path
            thisImgName = filePath.split('\\')[len(filePath.split('\\')) - 1] + '.jpg'
            thisFile = filePath + '\\' + thisImgName
            def file_iterator(file_name, chunk_size=512):
                # print('file_name:', file_name)
                with open(file_name, 'rb') as f:
                    while True:
                        c = f.read(chunk_size)
                        if c:
                            yield c
                        else:
                            break
            
    
            response = StreamingHttpResponse(file_iterator(thisFile))
            response['Content-Type'] = 'application/octet-stream'
            response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(thisImgName))
            return  response
    
    

    前端js

    
     var aElement = "<td><a href='#' id= " + a_id + "  onclick=" + "downloadImg(this)" + ">" + data[j][0].sn + "</a></td>";
    
    function downloadImg(e) {
    
        window.location.href= '/download/'+$(e)[0].id;
    
    }
    
    

    相关文章

      网友评论

        本文标题:2018-08-09Django 根据页面传递参数 下载文件

        本文链接:https://www.haomeiwen.com/subject/hphcbftx.html