{# {% for u in teacher_d.keys %}#}
{# {% for u in teacher_d.values %}#}
{% for k,u in teacher_d.items %}
<input type="text" value="{{ k }}">
<input type="text" value="{{ u }}">
{% endfor %}
user_dict = {
"1":"sb1",
"2":"sb2"
}
return render(request,"teacher.html",{"teacher_list":new_teacher_list,"teacher_d":user_dict})
基于form上传文件,我们一般会把文件上传到指定的路径,然后在数据库中存储文件和对应的路径的地址
前端上传文件的代码
<body>
<form method="post" action="/user_manager_app1/upload/" enctype="multipart/form-data">
{# enctype="multipart/form-data"如果在form标签中加上这一个属性,则上传的问题就不在request.POST中了,而在request.FILES中#}
<input type="text" name="name">
<input type="file" name="file">
<input type="submit" value="sum提交">
</form>
<h1>文件展示</h1>
<table border="1">
<caption>数据库中的文件</caption>
<thead>
<tr>
<th>文件名称</th>
<th>文件路径</th>
<th>上传时间</th>
<th>文件大小</th>
<th>文件操作</th>
</tr>
</thead>
<tbody>
{% for file in file_data %}
<tr>
<td>{{ file.file_name }}</td>
<td>{{ file.file_path }}</td>
<td>{{ file.file_time }}</td>
<td>{{ file.file_size }}</td>
<td>查看|删除</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
后端处理的代码
def upload(reqeust):
if reqeust.method.lower() == "get":
file_all = models.file.objects.all()
return render(reqeust,"upload.html",{"file_data":file_all})
else:
name = reqeust.POST.get("name")
file = reqeust.POST.get("file")
file_new = reqeust.FILES.get("file")
print("上传的文件的名称",file_new.name,"文件的大小",file_new.size)
file_path = os.path.join("static","upload",file_new.name)
with open(file_path,"wb") as f:
for chunk in file_new.chunks():
f.write(chunk)
models.file.objects.create(
file_path = file_path,
file_name = file_new.name,
file_time = time.ctime(),
file_size = file_new.size
)
return redirect("/user_manager_app1/upload/")
—————————————————————————————————————————————————————————————————————————–
通过ajax上传文件
前端代码–html
<h1>formData方式上传</h1>
<div id="imgs">
</div>
<input type="file" id="upload_file">
<input type="button" value="点击上传" id="upload_button">
<span id="errors"></span>
前端代码–jquery
<script src="/static/jq/jquery-3.3.1.js"></script>
<script>
$(function () {
upload_file()
})
function upload_file() {
$("#upload_button").bind("click",function () {
{# $("#errors").html()#}
var dict = new FormData()
dict.append("file",document.getElementById("upload_file").files[0])
$.ajax(
{
url:"/app1/upload_ajax/",
type:"POST",
data:dict,
success:function (data) {
data = JSON.parse(data)
if(data["state"] == "true"){
var img = document.createElement("img");
img.src = "/" + data["file_path"];
var father_ele = document.getElementById("imgs");
father_ele.appendChild(img);
{# window.location.reload()#}
}else {
$("#errors").html(data["error"])
}
},
processData:false,
contentType:false
}
)
})
}
</script>
这里有三个点需要注意
a、这里需要个formdata的对象,把我们上传的文件通过append的方法添加到这个formdata对象中,然后通过ajax把这个formdata对象发送给后端就可以了
先找到上传文件的input的标签,这里我们通过id去定位到input的标签


b、通过ajax直接把这个数据发送给后端,这里要注意,我们的data就是上面我们创建的formdata对象中

c、如果ajax要向后端发送数据,则必须要还有设置两个类型

最后我们看下后端的代码,后端也是要在request.Files中获取文件对象,然后写到本地就可以了
def upload_ajax(request):
import os
import json
method = request.method.lower()
if method == "get":
return render(request,"upload.html")
else:
res = {"state":"true","file_path":None,"error":""}
file = request.FILES.get("file")
print(file)
file_path = os.path.join("static","file",file.name)
try:
with open(file_path,"wb") as f:
for chunk in file.chunks():
f.write(chunk)
except Exception as e:
print(e)
res["state"] = "false"
res["error"] = "上传失败"
return HttpResponse(json.dumps(res))
else:
res["file_path"] = file_path
return HttpResponse(json.dumps(res))
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/20828.html