前端上传图片的三种方法
前端上传图片的三种方法
Django框架下,在前端上传文件,保存在数据库,并在前端不刷新页面显示上传图片。
- 利用XMLHttpRequest 对象和FormData对象上传文件
- Ajax上传文件
- 基于form表单和iframe自己实现ajax请求
1、首先创建数据库表
class Img(models.Model): path = models.CharField(max_length=128)
更新数据库
>python manage.py makemigrations
>python manage.py migrate
2、在Django后台views中定义函数
#前端上传文件,保存在数据库,并在前端不刷新页面显示上传图片 import os,json @csrf_exempt 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) ret = {'status': True, 'path': file_path} return HttpResponse(json.dumps(ret))
3、添加urls路径
url(r'^upload.html$', views.upload),
4、前端文件上传的三种方法
第一种、XML的方式上传文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .container img{ width: 200px; height:200px; } </style> </head> <body> <h1>图片列表</h1> <div class="container" id="imgs"> {% for img in img_list %} <img src="/{{ img.path }}"/> {% endfor %} </div> <input type="file" id="img"> <input type="button" value="提交XML" onclick="UploadXML()"/> <input type="button" value="提交JQ" onclick="Uploadjq()"/> <script src="/static/jquery-2.1.4.min.js"></script> <script> //XML的方式上传文件,并在页面不刷新显示图片 function UploadXML(){ var dic = new FormData(); dic.append('user', 'v1'); dic.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; $('#imgs').append(img); } } }; xml.send(dic); } </script> </body> </html>
第二种、ajax方式上传文件,并异步显示
<input type="file" id="img"> <input type="button" value="提交XML" onclick="UploadXML()"/> <input type="button" value="提交JQ" onclick="Uploadjq()"/> <script src="/static/jquery-2.1.4.min.js"></script> <script> //ajax方式上传文件,并异步显示 function Uploadjq(){ var dic = new FormData(); dic.append('user', 'v1'); dic.append('fafafa',document.getElementById('img').files[0]); $.ajax({ url:'/upload.html', type:'POST', data:dic, processData:false,// tell jQuery not to process the data 默认情况下jquary会对数据做处理 contentType:false, // tell jQuery not to set contentType dataType:'JSON', success: function (arg) { if (arg.status){ var img = document.createElement('img'); img.src = "/" + arg.path; $('#imgs').append(img); } } }) }
第三种、基于form表单和iframe自己实现ajax请求
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .container img{ width: 200px; height:200px; } </style> </head> <body> <h1>测试iframe功能</h1> <input type="text" id="url"/> <input type="button" value="点我" onclick="iframChange()"> <iframe id="ifr" src=""></iframe> <hr/> <h1>基于ifram实现form提交</h1> <form action="/upload.html" method="post" target="iframe_1" enctype="multipart/form-data"> <iframe style="display: none" id="iframe_1" name="iframe_1" src="" onload="loadIframe()"></iframe> <input type="text" name="user"/> <input type="file" name="fafafa"/> <input type="submit" value="确定"/> </form> <h1>图片列表</h1> <div class="container" id="imgs"> {% for img in img_list %} <img src="/{{ img.path }}"/> {% endfor %} </div> <script src="/static/jquery-2.1.4.min.js"></script> <script> //测试 function iframChange(){ var url = $('#url').val(); $('#ifr').attr('src',url); } //基于form表单和iframe自己实现ajax请求 function loadIframe(){ console.log(2); // 获取iframe内部的内容 var str_json = $('#iframe_1').contents().find('body').text(); var obj = JSON.parse(str_json); if (obj.status){ var img = document.createElement('img'); img.src = "/" + obj.path; $('#imgs').append(img); } } </script> </body> </html>