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 = "" + data[j][0].sn + "";

function downloadImg(e) {

    window.location.href= '/download/'+$(e)[0].id;

}

你可能感兴趣的:(2018-08-09Django 根据页面传递参数 下载文件)