在常见的用户注册页面,需要用户在本地选择一张图片作为头像,并同时预览。
常见的思路有两种:一是将图片上传至服务器的临时文件夹中,并返回该图片的url,然后渲染在html页面;另一种思路是,直接在本地内存中预览图片,用户确认提交后再上传至服务器保存。
这两种方法各有利弊,方法一很明显,浪费流量和服务器资源;方法二则加重了浏览器的负担,并且对浏览器的兼容性要求更高(在某些低版本中的IE浏览器不支持)。
以下是实现上述思路的方法:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <div style="margin-left: 30px; margin-top: 30px"> 9 <form action="">10 {% csrf_token %}11 <h3>用户注册</h3>12 <p>用户名:<input type="text" name="userName"></p>13 <p>密码:<input type="password" name="password"></p>14 <p>邮箱:<input type="text" name="email"></p>15 <input id="avatar" type="text" value="/static/images/sample.png" name="avatar" style="width: 400px"> {# 实际应用中要将该input标签隐藏,display:none; #}16 <p><input type="submit" value="注册"></p>17 </form>18 <div style="position: absolute; top: 85px; left: 300px;">19 <input id="avatarSlect" type="file" style="position: absolute;float: left; z-index: 10; opacity: 0;width: 100px; height: 100px;">20 <img id="avatarPreview" src="/static/images/sample.png" title="点击更换图片" style="position: absolute; z-index: 9; float: left; width: 100px; height: 100px">21 </div>22 </div>23 </body>24 25 <script src="/static/jquery-3.2.1.js?1.1.11"></script>26 <script>27 $(function () {28 bindAvatar();29 });30 function bindAvatar() {31 if(window.URL.createObjectURL){32 bindAvatar3();33 }else if(window.FileReader){34 bindAvatar2();35 }else {36 bindAvatar1();37 }38 }39 40 /*Ajax上传至后台并返回图片的url*/41 function bindAvatar1() {42 $("#avatarSlect").change(function () {43 var csrf = $("input[name='csrfmiddlewaretoken']").val();44 var formData=new FormData();45 formData.append("csrfmiddlewaretoken",csrf);46 formData.append('avatar', $("#avatarSlect")[0].files[0]); /*获取上传的图片对象*/47 $.ajax({48 url: '/upload_avatar/',49 type: 'POST',50 data: formData,51 contentType: false,52 processData: false,53 success: function (args) {54 console.log(args); /*服务器端的图片地址*/55 $("#avatarPreview").attr('src','/'+args); /*预览图片*/56 $("#avatar").val('/'+args); /*将服务端的图片url赋值给form表单的隐藏input标签*/57 }58 })59 })60 }61 /*window.FileReader本地预览*/62 function bindAvatar2() {63 console.log(2);64 $("#avatarSlect").change(function () {65 var obj=$("#avatarSlect")[0].files[0];66 var fr=new FileReader();67 fr.onload=function () {68 $("#avatarPreview").attr('src',this.result);69 console.log(this.result);70 $("#avatar").val(this.result);71 };72 fr.readAsDataURL(obj);73 })74 }75 /*window.URL.createObjectURL本地预览*/76 function bindAvatar3() {77 console.log(3);78 $("#avatarSlect").change(function () {79 var obj=$("#avatarSlect")[0].files[0];80 var wuc=window.URL.createObjectURL(obj);81 $("#avatarPreview").attr('src',wuc);82 $("#avatar").val(wuc);83 {# $("#avatarPreview").load(function () {#} /*当图片加载后释放内存空间,但在jQuery3.2.1中会报错。浏览器关闭后也会自动释放*/84 {# window.URL.revokeObjectURL(wuc);#}85 {# })#}86 })87 }88 89 </script>90 </html>
1 from django.shortcuts import render, HttpResponse 2 3 4 def test(request): 5 return render(request, 'test.html') 6 7 8 def upload_avatar(request): 9 file_obj = request.FILES.get('avatar')10 file_path = os.path.join('static/images', file_obj.name)11 with open(file_path, 'wb') as f:12 for chunk in file_obj.chunks():13 f.write(chunk)14 return HttpResponse(file_path)
1 from django.conf.urls import url2 from django.contrib import admin3 from home import views as homeViews4 5 urlpatterns = [6 url(r'^admin/', admin.site.urls),7 url(r'^upload_avatar/', homeViews.upload_avatar), # 上传头像8 url(r'^test/', homeViews.test), # 测试页面9 ]
Atas ialah kandungan terperinci 3种上传图片的方法实例. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!