几种方式实现文件上传

1.基于form表单实现文件上传

html:

  <form action="/app/test/" method="post" enctype="multipart/form-data">

    <input type="text" name="name"/>
    <input type="file" name="fafafa" id="f"/>
    <input type="submit" value="提交"/>
  </form>
views.py:

name = request.POST.get('name')
fafafa = request.FILES.get('fafafa')
import os
file_path = os.path.join('static','upload',fafafa.name)//设置存储路径
f = open(file_path,'wb')
for chunk in fafafa.chunks()://写入文件
 f.write(chunk)
f.close()
models.Image.objects.create(path=file_path)//将文件路径存入数据库
print(fafafa,fafafa.size,fafafa.name)

 2.基于ajax实现文件上传(利用FormData对象实现)

①:原生ajax方式

html:

<input type="file" id="img"/>
<button id="tj">提交</button>
<div id="d">
{% for item in image_list %}
<img src="\{{ item.path }}" class="im">
{% endfor %}
</div>
$('#tj').click(function () {
var dic = new FormData();//利用FormData对象
dic.append('user','lh');
dic.append('fafafa',document.getElementById('img').files[0]);
console.log(document.getElementById('img').files);

var xml = new XMLHttpRequest();
xml.open('post','/app/upload_file/',true);
xml.onreadystatechange = function () {
if(xml.readyState == 4){//上传成功后,插入到当前页面,显示出来
data = xml.responseText;
obj = JSON.parse(data);
if(obj.status){
var img = document.createElement('img');
img.src ='/'+obj.path;
img.className = 'im';
$('#d').append(img);
}
}
};
xml.send(dic)
});
②:基于jQuery实现
html:
<input type="file" id="img"/>
<button id="aj">提交</button>
 $('#aj').click(function () {
var dic = new FormData();
dic.append('user','lh');
dic.append('fafafa',document.getElementById('img').files[0]);
$.ajax({
url:'/app/upload_file/',
type:'POST',
dataType:'JSON',
data:dic,
processData:false,
contentType:false,
success:function (obj) {
console.log(obj);
if(obj.status){
var img = document.createElement('img');
img.src = '/'+obj.path;
img.className = 'im';
$('#d').append(img)
}
}
})
})
});

views.py:
def upload_file(request):
if request.method == 'GET':
image_list = models.Image.objects.all()
return render(request,'upload_file.html',{'image_list':image_list})
elif request.method == 'POST':
fafafa = request.FILES.get('fafafa')
import os
file_path = os.path.join('static', 'upload', fafafa.name)
print(file_path)
f = open(file_path, 'wb')
for chunk in fafafa.chunks():
f.write(chunk)
f.close()
models.Image.objects.create(path=file_path)
ret = {
'status':True,
'path':file_path//返回图片路径
}
import json
return HttpResponse(json.dumps(ret))
3.基于iframe实现文件上传
html:
<form action="/app/upload_file/" method="post" target="iframe_1" enctype="multipart/form-data">
<input type="text" name="name" id="name"/>
<input type="file" name="fafafa" id="f"/>
<iframe src="" name="iframe_1" id="fr" onload="fun1();" style="display: none" ></iframe>
<input type="submit" value="tijiao"/>
</form>

<div id="d">
{% for item in image_list %}
<img src="\{{ item.path }}" class="im">
{% endfor %}
</div>
<script>
function fun1() {
var v = $('#fr').contents().find('body').text();//从iframe中取出客户端返回值
obj = JSON.parse(v);
if(obj.status){
var url = '/'+obj.path;
var img = document.createElement('img');
img.src=url;
img.className='im';
$('#d').append(img);
}
}
<script/>
views.py:
def upload_file(request):
if request.method == 'GET':
image_list = models.Image.objects.all()
return render(request,'upload_file.html',{'image_list':image_list})
elif request.method == 'POST':
fafafa = request.FILES.get('fafafa')
import os
file_path = os.path.join('static', 'upload', fafafa.name)
print(file_path)
f = open(file_path, 'wb')
for chunk in fafafa.chunks():
f.write(chunk)
f.close()
models.Image.objects.create(path=file_path)
ret = {
'status':True,
'path':file_path//返回图片路径
}
import json
return HttpResponse(json.dumps(ret))
 
 
 

 

posted @ 2017-11-28 10:53  Jcp_Lee  阅读(300)  评论(0)    收藏  举报