使用原生Ajax 或jQuery Ajax 进行文件上传时,会遇到 IE 兼容问题,低版本IE,如IE6 没有XmlHttpRequest对象 和 FormData 对象 ,而使用 iframe 可已做到异步文件上传
iframe 文件上传依赖:
依赖 <form entype=enctype="multipart/form-data"></form> 标签
注意事项:
1、给form 添加 targer = iframe<name> 服务器返回数据会跳转到 内嵌的iframe里
2、服务器返回数据后 ,iframe 载人完毕会立刻执行 onload 事件 (js) load(jquery) 。
2、我们一般从 JS 里对服务器返回的数据进行处理,而不是内嵌的 iframe ,所以需要获取 iframe内容
3、iframe 生成的html 为#document 所以不能用一般的 DOM操作,需要用.contents()
html
<form action="/iframe/" method="post" enctype="multipart/form-data" target="iframe1">
<input type="file" name="file">
<iframe name="iframe1" frameborder="0" style="display: none"></iframe>
<input type="submit" value="提交">
</form>
<script>
// 鼠标点击提交按钮,服务器会返回数据,iframe 执行onload 事件
// 获取 iframe 内容(text) 用.contents()查找
// 将得到的 text 字符串序列化成对象,方便操作
$('input[type=submit]').click(function () {
$('iframe[name=iframe1]').load(function () {
var text = $('iframe[name=iframe1]').contents().find('body').text()
var obj = JSON.parse(text)
console.log(obj)
})
})
</script>
views.py
def iframe(request):
if request.method == 'POST':
ret = {'status':'ok','data':None}
file = request.FILES.get('file',None)
import os
if file:
# file_path = os.path.join('static','upload',file.name)
# 推荐用下面方法拼接图片路径,上面方法,返回的路径是反斜杠 'static\upload\xxx'
file_path = os.path.join('static/upload/',file.name)
with open (file_path,'wb') as f:
for item in file.chunks():
f.write(item)
return HttpResponse(json.dumps(ret))
return render(request,'iframe.html')
文件预览:
步骤:
1、文件上传后,服务器返回文件路径
file_path = os.path.join('static/upload/',file.name)
ret['data'] = file_path
---> 'static/upload/文件名'
2、通过JS 对文件路径进行处理
'/static/upload/文件名' 访问图片需要再返回的路径前面再加1个'/'
3、处理后添加<img>标签并设置<img src>属性
imgTag = document.createElement('img') js 方法
imgTag.src='/' + obj.data
4、第二次上传图片的时候,需要把前面一次的 <img>标签删除
xxx.empty() --jquery方法
文件上传加文件预览完整demo
views.py
def iframe(request):
if request.method == 'POST':
ret = {'status':'ok','data':None}
file = request.FILES.get('file',None)
import os
if file:
file_path = os.path.join('static/upload/',file.name)
ret['data'] = file_path # 返回文件路径
with open (file_path,'wb') as f:
for item in file.chunks():
f.write(item)
return HttpResponse(json.dumps(ret))
return render(request,'iframe.html')
html
<body>
<form action="/iframe/" method="post" enctype="multipart/form-data" target="iframe1">
<input type="file" name="file">
<iframe name="iframe1" ></iframe>
<input type="submit" value="提交">
</form>
<div class = 'img'></div>
</body>
js
<script>
$(function(){
$('input[type=submit]').click(function () {
$('iframe[name=iframe1]').load(function () {
var text = $('iframe[name=iframe1]').contents().find('body').text();
console.log(text)
var obj = JSON.parse(text)
$('.img').empty() // 第二次上传,如果img存在,删除img
var imgTag = document.createElement('img') // 创建 <img> 标签
imgTag.src = '/'+obj.data // 设置 img src 路径
$('.img').append(imgTag) // 在div 下面添加标签
})
})
})
</script>