在Django框架获取多个数据以及实现文件上传功能这篇文章中,我们是通过form表单上传文件,这里的文件就以图片为例,两者都是一样的。form表单的方式就不在说了,不会自己去看一下。现在我们通过ajax来实现文件上传,那么创建upload路由规则和对应的视图函数。
第一种方式,通过xhr对象
视图函数
def upload_file(request):
username = request.POST.get('username') #测试用户名
file_data = request.FILES.get('file') #拿到上传的文件
with open(file_data.name,'wb') as f:
for item in file_data.chunks():
f.write(item)
reg = {'code': True, 'data': request.POST.get('username')} # 定义一个字典
import json # 转换为字符串
return HttpResponse(json.dumps(reg))
def upload(request): #文件上传页面
return render(request, 'upload.html')
upload.html
<input type="file" id="file">
<input type="botton" value="xhr提交" onclick="xhrSubmit();">
<script>
function xhrSubmit() {
var file_obj=document.getElementById('file').files[0]; //拿到上传的文件
var form_data=new FormData();
form_data.append('username','鳄鱼君Ba');
form_data.append('file',file_obj);
var xhr=new XMLHttpRequest();
xhr.open("POST","/upload_file/",true);
xhr.onreadystatechange=function () {
if(xhr.readyState===4)
var obj=JSON.parse(xhr.responseText);
console.log(obj);
}
xhr.send(form_data);
}
</script>
第一种方式,通过jQuery
<input type="file" id="file">
<input type="botton" value="jQuery提交" onclick="jqSubmit();">
<script type="text/javascript" src="/static/jquery-3.4.1.js"></script>
<script>
function jqSubmit() {
var file_obj=document.getElementById('file').files[0]; //拿到上传的文件
var form_data=new FormData();
form_data.append('username','鳄鱼君Ba');
form_data.append('file',file_obj);
$.ajax({
url:'/upload_file/',
type:'POST',
data:form_data,
processData:false,
contentType:false,
success:function (data) {
console.log(data);
}
})
}
</script>
第一种方式,通过Iframe
<form action="/upload_file/" method="post" enctype="multipart/form-data" target="a1"> <!--让iframe跟form建立关系-->
<iframe id="a1" name="a1" ></iframe>
<input type="file" name="file">
<input type="submit" onclick="iframeSubmit();" value="iframe提交">
</form>
<script type="text/javascript" src="/static/jquery-3.4.1.js"></script>
<script>
// .load() , .error() , .unload() ,已经不在支持,jquery1.8版本之后的都无法再使用;
//使用 .on("load",function(){.................}) 来代替 .load() 即可;
function iframeSubmit() {
$('#a1').on("load",function () {
var text=$('#a1').contents().find('body').text();
var obj=JSON.parse(text);
console.log(obj);
})
}
</script>
iframe兼容性更好,在所有的浏览器都适用,一般图片上传都是采用iframe来实现。那么下面来实现图片的预览功能,这里可以在static文件夹下新建一个imags文件夹用于上传文件的路径。注意配置静态文件路径!!否则你的图片显示不出来:
def upload_file(request):
import os
file_data = request.FILES.get('file') #拿到上传的文件
file_path = os.path.join('static/images/', file_data.name) #新建目录存放上传的图片
with open(file_path,'wb') as f:
for item in file_data.chunks():
f.write(item)
reg = {'code': True, 'data': file_path} # 将路径存放到data中
import json # 转换为字符串
return HttpResponse(json.dumps(reg))
def upload(request): #文件上传页面
return render(request, 'upload.html')
upload.html
<form action="/upload_file/" method="post" enctype="multipart/form-data" target="a1"> <!--让iframe跟form建立关系-->
<iframe id="a1" name="a1" ></iframe>
<input type="file" name="file">
<input type="submit" onclick="iframeSubmit();" value="iframe提交">
</form>
<div id="image"></div>
<script type="text/javascript" src="/static/jquery-3.4.1.js"></script>
<script>
// .load() , .error() , .unload() ,已经不在支持,jquery1.8版本之后的都无法再使用;
//使用 .on("load",function(){.................}) 来代替 .load() 即可;
function iframeSubmit() {
$('#a1').on("load",function () {
var text=$('#a1').contents().find('body').text();
var obj=JSON.parse(text);
$('#image').empty(); //清空原来的
var img_tag=document.createElement('img'); //创建img标签
img_tag.src="/"+obj.data; //设置src属性值
$('#image').append(img_tag);
})
}
</script>
到此为止,三种方式就介绍完了,为了让上传图片更加合理,在上传图片的时候直接提交,不需要点击操作:
<form id="file1" action="/upload_file/" method="post" enctype="multipart/form-data" target="a1"> <!--让iframe跟form建立关系-->
<iframe id="a1" name="a1" style="display: none"></iframe>
<input type="file" name="file" onchange="changeFile();">
</form>
<div id="image"></div>
<script type="text/javascript" src="/static/jquery-3.4.1.js"></script>
<script>
function changeFile() {
$('#a1').on("load",function () {
var text=$('#a1').contents().find('body').text();
var obj=JSON.parse(text);
$('#image').empty(); //清空原来的
var img_tag=document.createElement('img'); //创建img标签
img_tag.src="/"+obj.data; //设置src属性值
$('#image').append(img_tag);
})
$('#file1').submit();
}
</script>
声明:1. 本站所有资源来源于用户上传和网络,因此不包含技术服务请大家谅解!如有侵权请邮件联系客服!
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!