django in to upload files through the file and Ajax

First, to upload files form form

  1. html template

< Form Action = "/ index /" Method = "POST" enctype = "multipart / form-data" > 
# enctype written in the form attribute = "multipart / form-data" submit this form to support the form of data files { % csrf_token%} avatar < INPUT type = "File" name = "touxiang" ID = "File" > < br > < label for = "name" > username </ label > < INPUT type = "text" ID = " name " name="username"> <button id="btn">提交</button> </form>

  2. written views view

DEF index (Request):
     IF request.method == ' the GET ' :
         return the render (Request, ' index.html ' )
     the else : 
        the uname = request.POST.get ( ' username ' ) 
        File = request.FILES.get ( ' touxiang ' ) # acquired file to the file data acquired by .FILES.get () 
        file_name = file.name 
        path = the os.path.join (settings.BASE_DIR, ' statics to ' , ' IMG ', file_name) # to splice the file path 
        with Open (path, ' WB ' ) AS F: # will be written to the local file 
            for I in File: 
                f.write (I) 
        return the HttpResponse (the uname)

  When receiving the contents of the documents in time to the back-end reception FILES, not those who only received the file name,

  After receiving a request.FILES.get ( 'file'), will receive a similar data type of the file handle, the file can be read through the cycle, when the file is a video, they can use the handle .chunks () receiving fixed size file, the memory is filled to prevent

of chunks are () returns the size of the default bit tested 65536b, is 64kb, the maximum is 2.5MB, a generator

Two, Ajax to upload files

  1. In the HTML template

    $ ( ' #Btn ' ) .click (function () { 
        var FormData = the FormData new new (); # Ajax upload files, the need for this type, it will add the key-type processed into formata 
        formdata.append ( ' the uname ' , $ ( ' to the #NAME ' ) .val ()); # add key-value pairs is to append, note writing, using commas between the key and value separated 
        formdata.append ( ' Files ' , $ ( ' #file ' ) [0] .files [0]); 
        formdata.append ( ' csrfmiddlewaretoken ' , $ ( ' [name = csrfmiddlewaretoken] ' ) .val ()); #Remember csrf_tocken 
        $ .ajax ({
             ' URL ' : " {% URL 'index'}% " ,
             ' type ' : ' POST ' ,
             ' data ' : formdata, # add data into good formdata here 
            processData: false, // do not process the data 
            contentType: to false, // do not set content type 
            Success: function (RES) { 
                the console.log (RES) 
            } 
        }) 
     })

  2. In view of the function

DEF index (Request):
     IF request.method == ' the GET ' :
         return the render (Request, ' index.html ' )
     the else : 
        name = request.POST.get ( ' the uname ' ) # Get the POST request sent from the data 
        file request.FILES.get = ( ' TOU ' ) # get the data uploaded file 
        file_name = file.name # get the file name 
        path = os.path.join (settings.BASE_DIR, ' statics ' , ' img ', file_name) # splicing file path 
        with Open (path, ' WB ' ) AS F: # will be written to the local file 
            for I in file.chunks (): 
               f.write (I)

Three, JsonResponse

DEF index (Request):
     IF request.method == ' the GET ' :
         return the render (Request, ' index.html ' )
     the else :
         # dd = { 'K1': 'V1', 'K2': 'V2'} 
        # = json.dumps dd (dd) 
        # return the HttpResponse (dd, the content_type = 'file application / JSON') # when sending a transmission cntent_type = 'application / json' response body, is sent to the template will automatically call ajax ajax deserialization, there is no need to manually deserialize the 
        # in python also have, that is the object JsonResponse 
        JsonResponse HttpResponse object is a subclass, designed to generate coded JSON response
         from Django.HTTP Import JsonResponse # import JsonResponse
        = {dd ' K1 ' : ' V1 ' , ' K2 ' : ' V2 ' }
         return jsonResponse (dd) # This eliminates the need to manually serialized, not necessary to manually write a response body 
        dd = [11,22 , 33 is ]
         return jsonResponse (dd, Safe = False) # when the sequence of a non-dictionary when you need safe = false,

Four, the sequence of json date data type Method

Import json
 from datetime Import datetime
 from datetime Import DATE 

# of json data format of data containing the date converting 
class JsonCustomEncoder (json.JSONEncoder):
     DEF default (Self, Field):
         IF the isinstance (Field, datetime):
             return field.strftime ( ' % Y-M-% D%% H:% M:% S ' )
         elif the isinstance (Field, DATE):
             return field.strftime ( ' %% M-% Y-D ' )
         the else :
             returnjson.JSONEncoder.default (Self, Field) 


D1 = DateTime.Now () 

dd = json.dumps (D1, CLS = JsonCustomEncoder) # When it calls json when he just can not write the data to be serialized, later to be = JsonCustomEncoder write CLS 
Print (dd)

 

Guess you like

Origin www.cnblogs.com/wang-xing-hao/p/11266487.html