{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>网页上传</title>
</head>
<body>
<h1> 欢迎使用网页上传文件 </h1>
<form>
{% csrf_token %}
用户名: <input type="text" name="user">
头像: <input type="file" name="head-png" id="file" multiple>
<input type="button" id="ajax-submit" value="提交">
<span style="color:#00ff04;font-size: 12px;" id="info"></span>
</form>
<script src="{% static 'jquery.js' %} "></script>
<script>
$("#ajax-submit").click(function () {
var formdata=new FormData(); // ajax上传文件的时候,需要这个类型,它会将添加给它的键值对加工成formdata的类型
formdata.append("user",$("#user").val()); // 添加键值的方法是append,注意写法,键和值之间是逗号
formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val());
formdata.append("head-png",$("#file")[0].files[0]);
$.ajax({
url:"/app01/index/",
type:"post",
data:formdata,
processData: false , // 不处理数据
contentType: false, // 不设置内容类型
success:function (data) {
console.log(data)
var resStr = JSON.parse(data)
if (resStr['code'] === "0000"){
var spanEle = document.createElement('span');
$('#info').text(resStr['msg']);
}
}
})
})
</script>
</body>
</html>
views.py
import os.path
from django.shortcuts import render,HttpResponse,redirect
from django.views import View
from django.conf import settings
# Create your views here.
class index(View):
html = 'h5_upload_file.html'
def get(self,request):
# print(request.GET) # <QueryDict: {}> GET请求数据
return render(request,self.html)
def post(self,request):
user = request.POST.get('user')
file_obj = request.FILES.get('head-png')
file_name = os.path.join(settings.BASE_DIR,'img',file_obj.name) # project/img/filename
with open(file_name,'wb') as f:
for i in file_obj:
f.write(i)
res = '{"code":"0000","msg":"%s upload success!","url":"/app01/msg/"}' % file_obj.name
return HttpResponse(res)