一、form表单上传 |
1.页面代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="{% url ‘upload‘ %} " method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="img"> <input type="submit"> </form> </body> </html>
2.后端view函数处理
def upload(request): if request.method=="GET": return render(request,‘upload.html‘) elif request.method=="POST": res={"status":"success","code":999} img_obj=request.FILES.get(‘img‘)#获取文件对象 with open(os.path.join(‘static‘,img_obj.name),"wb") as f: for chunk in img_obj.chunks(chunk_size=1024): f.write(chunk) return HttpResponse(json.dumps(res))
二、利用Jquery中ajax+FormData实现上传文件 |
上传步骤:
1.页面代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="{% url ‘upload‘ %} " method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="img"> </form> <span style="padding: 5px;color: royalblue" onclick="Jqajax();">jq上传</span> <script type="text/javascript" src="/static/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="/static/jquery.cookie.js"></script> <script> function Jqajax() { var file_obj=$(‘input[name="img"]‘)[0].files[0];//获取dom形式的文件对象 var form_obj=new FormData(); //创建formdata对象 form_obj.append(‘img‘,file_obj); //将文件对象加载formdata中 $.ajaxSetup({ //设置csrf_token beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", $.cookie("csrftoken")); } }); $.ajax({ type: ‘POST‘, url: ‘{% url ‘upload‘ %}‘, data: form_obj,//指明发送的文件对象 processData: false, // 告诉jquery要传输data对象 contentType: false, // 告诉jquery不需要增加请求头对于contentType的设置 success: function (data) { console.log(data) } }) } </script> </body> </html>
后端处理逻辑不变