form

templates

<form enctype=\"multipart/form-data\" method=\"POST\" action=\"******\"> 
   <input type=\"file\" name=\"file\" />
   <br /> 
   <input type=\"submit\" value=\"上传文件\" /> 
</form>

views

def upload(request):
    file = request.FILES.get(\'file\')
    path=os.path.join(\'static/fileup\',file.name)
    f=open(path,\'wb\')
    for chunk in file.chunks(chunk_size=1024):
        f.write(chunk)
    f.close()    
    return render(request, \'upload_Succee.html\')

ajax

templates

<input type=\"file\" name=\"file\" />
<a  =\"uploadFile2();\" style=\"cursor: pointer; display: inline-block;>JQuery-Ajax上传</a>
< >
function uploadFile2() {
#Jquery转换为dom对象:$(\"#img\")[0].files[0];其中$(\"#img\")是jquery对象,$(\"#img\")[0]是dom对象                        
            var fileobj = $(\"type=\'file\'\")[0].files[0];
            var form = new FormData();
            form.append(\"file\", fileobj);
            form.append(\"uesr\", \'jw\');
            $.ajax({
                type: \'POST\',
                url: \'******\',
                data: form,
                processData: false, # 告诉jquery要传输data对象
                contentType: false,   # 告诉jquery不需要增加请求头对于contentType的设置
            }).done(fuction(data){
                    #data为返回的json对象
                    #请求成功执行的代码块
            }).fail(function(){
                    #请求失败执行的代码块
            })
        }
</ >

views

from django.http import JsonResponse
import os
def upload(request):
    file = request.FILES.get(\'file\')
    path=os.path.join(\'static/fileup\',file.name)
    f=open(path,\'wb\')
    for chunk in file.chunks(chunk_size=1024):
        f.write(chunk)
    f.close()    
    return JsonResponse({\"flag\":\"succeed\"})

 

收藏 打印