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

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;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。