django model 上传下载文件

import os
from demo1 import settings


def upload_to(instance, filename):
    return os.path.join(settings.BASE_DIR,"static", instance.name, filename) # 注意此处没有斜杠


class FF(models.Model):
    id = models.AutoField(primary_key=True)
    pdf = models.FileField(upload_to=upload_to, verbose_name="文件上传")
    name = models.CharField(max_length=256, blank=True, null=True)

  

def post(self,request):
    data = request.POST
    data = dict(data)
    print(data) # {'id': ['1'], 'name': ['张三']}
    real_dict = {}
    for k,v in data.items():
        real_dict[k] = v[0]
    file = request.FILES.get("file",None)
    if not file:
        return HttpResponse("没有文件!")

    obj = FF.objects.create(pdf=file,**real_dict)
    print(obj) # FF object (1)
    print(type(obj)) #<class 'app01.models.FF'>
    print(obj.__dict__) 
    # {'_state': <django.db.models.base.ModelState object at 0x106abec18>, 'id': '1', 'pdf': '/Users/。。。。。1/static/张三/sql查询语句.pdf', 'name': '张三'}
    return HttpResponse("ok!")

 

path('down/', down),

  

from django.http import FileResponse
from django.utils.encoding import escape_uri_path
from demo1 import settings
def down(request):
data = request.GET
data = dict(data)
print(data)
real_dict = {}
for k, v in data.items():
real_dict[k] = v[0]

url = settings.BASE_DIR+settings.STATIC_URL+real_dict["name"]+"/"+real_dict["file"]
file = open(url,"rb")
response = FileResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(real_dict["file"]))
return response

  

 

    def get(self,request):
        data = request.GET
        data = dict(data)
        print(data)
        real_dict = {}
        for k,v in data.items():
            real_dict[k] = v[0]
        obj = FF.objects.filter(id=real_dict["id"]).values("id","name","pdf").first()
        print(obj)
        print(type(obj))
        return JsonResponse({"data":obj,"msg":"ok"})

  

 

 

 

  

posted @ 2019-11-25 23:13  real-admin  阅读(804)  评论(0编辑  收藏  举报