1.原生实现上传
//首先new一个XMLRequest对象
xml=new XMLHttpRequest();
//上传路径以及提交方式,true表示以异步方式发送数据
xml.open('post','/upload.html',true);
//发送数据
xml.send("k1=v1;k2=v2;");
2.jQuery实现
$.ajax({
url:'/upload.html',
data:{'k1':'v1','k2':'v2'}
});
3.FormData对象(相当于一个字典,不仅仅可以承载字符串,还能承载文件)
dict=new FormData();
//生成一个键值对
dict.append('k1','v1');
//发送文件
dict.append('k2',文件对象);
xml.send(dict);
后台代码实例:
import os
def upload(request):
if request.method=="GET":
img_list=models.Img.objects.all()
return render(request,'upload.html',{'img_list':img_list})
elif request.method=="POST":
user = request.POST.get('user')
fafafa = request.POST.get('fafafa')
obj = request.FILES.get('fafafa')
file_path = os.path.join('static', 'upload', obj.name)
f = open(file_path, 'wb')
for chunk in obj.chunks():
f.write(chunk)
f.close()
models.Img.objects.create(path=file_path)
# return redirect('/upload.html')
ret={'status':True,'path':file_path}
import json
return HttpResponse(json.dumps(ret))
前端代码实例(包括原生js,jQuery):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container img{
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<!--<form action="/upload.html" method="post" enctype="multipart/form-data">
<input type="text" name="user">
<input type="file" name="fafafa">
<input type="submit" value="上传">
</form>
{% for img in img_list %}
<img src="/{{ img.path }}">
{% endfor %}
-->
<input type="file" name="fafafa" id="img">
<input type="button" value="提交xml" onclick="UploadXML()">
<input type="button" value="提交jquery" onclick="uploadjQuery()">
<div class="container" id="imgs">
{% for img in img_list %}
<img src="/{{ img.path }}">
{% endfor %}
</div>
</body>
<script src="/static/jquery-3.4.1.min.js"></script>
<script>
function UploadXML() {
var dict=new FormData();
dict.append('user','v1');
dict.append('fafafa',document.getElementById('img').files[0]);
var xml=new XMLHttpRequest();
xml.open('post','/upload.html',true);
//回调函数
xml.onreadystatechange=function(){
if (xml.readyState ==4){
var obj=JSON.parse(xml.responseText)
if (obj.status){
var img=document.createElement('img');
img.src="/"+obj.path;
document.getElementById("imgs").appendChild(img);
}
}
};
xml.send(dict);
}
function uploadjQuery() {
var dict=new FormData();
dict.append('user','v1');
dict.append('fafafa',document.getElementById('img').files[0]);
$.ajax({
url:'/upload.html',
type:"POST",
data:dict,
//让数据不被处理
processData:false,
contentType:false,
dataType:'JSON',
success:function (arg) {
if (arg.status){
console.log(arg);
var img=document.createElement('img');
img.src="/"+arg.path;
$('#imgs').append(img);
}
}
});
}
</script>
</html>
版权声明:本文为weixin_44301439原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。