django 文件的上傳

上傳文件

  1. form表單上傳文件html

    <form action="/upload/" method="post" enctype="multipart/form-data"> 
      {% csrf_token %}
      頭像: <input type="file" name="head-pic">
      用戶名: <input type="text" name="username">
      <input type="submit">
    </form>
    
    
    def upload(request):
        if request.method == 'GET':
    
            return render(request,'upload.html')
        else:
            print(request.POST)  #拿到的是post請求的數據,可是文件相關數據須要用request.FILES去拿
            print(request.FILES) #<MultiValueDict: {'head-pic': [<InMemoryUploadedFile: 1.png (image/png)>]}>
            file_obj = request.FILES.get('head-pic')
            print(file_obj)
            file_name = file_obj.name
    
    
            # f = open('xx.txt','rb')
            # with open('xx.txt','wb') as f2:
            #     for i in f:
            #         f2.write(i)
            import os
            path = os.path.join(settings.BASE_DIR,'statics','img',file_name)
            with open(path,'wb') as f:
                for i in file_obj:
                    f.write(i)
             #for chunk in  file_obj.chunks():
                #    f.write(chunk)
    
            return HttpResponse('ok')
  2. ajax上傳文件ajax

    var formdata = new FormData();
    formdata.append('user',$('#username').val())
    formdata.append('csrfmiddlewaretoken',$('[name=csrfmiddlewaretoken]').val())
    formdata.append('file',$('#file')[0].files[0])
    $.ajax({
     url:'/upload/',
     type:'post',
     data:formdata,
     success:function(response){
         response
    
     }
    
    })
    
    def upload(request):
        if request.method == 'GET':
    
            return render(request,'upload.html')
        else:
            print(request.POST)  #拿到的是post請求的數據,可是文件相關數據須要用request.FILES去拿
            print(request.FILES) #<MultiValueDict: {'head-pic': [<InMemoryUploadedFile: 1.png (image/png)>]}>
            file_obj = request.FILES.get('head-pic')
            print(file_obj)
            file_name = file_obj.name
    
    
            # f = open('xx.txt','rb')
            # with open('xx.txt','wb') as f2:
            #     for i in f:
            #         f2.write(i)
            import os
            path = os.path.join(settings.BASE_DIR,'statics','img',file_name)
            with open(path,'wb') as f:
                for i in file_obj:
                    f.write(i)
             #for chunk in  file_obj.chunks():
                #    f.write(chunk)
    
            return HttpResponse('ok')

JsonResponse

def index(request):

​   d1 = {'name':'chao'}

​   import json

​   return HttpResponse(json.dumps(d1))  -- success:function(res){ var a = JSON.parse(res) }

​   return HttpResponse(json.dumps(d1),content-type='application/json') --success:function(res){res--自定義對象,不須要本身在反序列化了}

​   return JsonResponse(d1)

​   d1 = [11,22]  #非字典類型的數據都須要加safe=False

​   return JsonResponse(d1,safe=False)

獲取多對多數據的時候

authors = request.POST.getlist('authors')

json序列化時間日期類型的數據的方法

import json
from datetime import datetime
from datetime import date

#對含有日期格式數據的json數據進行轉換
class JsonCustomEncoder(json.JSONEncoder):
    def default(self, field):
        if isinstance(field,datetime):
            return field.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(field,date):
            return field.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self,field)


d1 = datetime.now()

dd = json.dumps(d1,cls=JsonCustomEncoder)
print(dd)
相關文章
相關標籤/搜索