上传图片或者文件
以后绝对会用到 使用ajax上传文件或者图片
urls:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.contrib import admin from django.urls import path from one import views urlpatterns = [ path('admin/', admin.site.urls), path('upload_img/',views.upload_img), #上传图片 path('form_data_upload/',views.form_data_upload), path('upload_file/',views.upload_file), #上传文件 path('iframe_upload_img/',views.iframe_upload_img), path('upload_iframe/', views.upload_iframe), ]
views:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.shortcuts import render,redirect,HttpResponse import os import uuid def upload_img(request): ''' 上传图片 :param request: :return: ''' if request.method == "GET": return render(request,'upload_img.html') user = request.POST.get('user') avatar = request.POST.get('avatar') print(user,avatar) return HttpResponse('上传成功') def form_data_upload(request): """ ajax上传文件 :param request: :return: """ img_upload = request.FILES.get('img_upload') file_name = str(uuid.uuid4()) + "." + img_upload.name.rsplit('.', maxsplit=1)[1] #取到你的 按照.分割后的 后缀名 就是后面的jpg或者png img_file_path = os.path.join('static', 'imgs', file_name) #让你的这个图片存储在这里 进行地址拼接 with open(img_file_path, 'wb') as f: for line in img_upload.chunks(): #chunks 是按照块来循环的这样和按照和的没有区别 f.write(line) return HttpResponse(img_file_path) # 把你的地址返回出去 然后进行你的地址的接收 def upload_file(request): ''' 上传文件 :param request: :return: ''' if request.method == "GET": return render(request,'upload_file.html') user = request.POST.get('user') avatar = request.FILES.get('avatar') with open(avatar.name,'wb') as f: for line in avatar.chunks(): f.write(line) return HttpResponse('上传成功') USER_LIST = [] def iframe_upload_img(request): ''' 这是iframe :param request: :return: ''' if request.method == "GET": return render(request,'iframe_upload_img.html') user = request.POST.get('user') pwd = request.POST.get('pwd') avatar = request.POST.get('avatar') USER_LIST.append( { 'user':user, 'pwd':pwd, 'avatar':avatar } ) return redirect('/index/') def upload_iframe(request): ''' 你的伪造的ajax ifram和form的组成的访问 :param request: :return: ''' ret = {'status':True,'data':None} try: avatar = request.FILES.get('avatar') file_name = str(uuid.uuid4()) + "." + avatar.name.rsplit('.', maxsplit=1)[1] img_file_path = os.path.join('static', 'imgs', file_name) with open(img_file_path, 'wb') as f: for line in avatar.chunks(): f.write(line) ret['data'] = os.path.join("/",img_file_path) except Exception as e: ret['status'] = False ret['error'] = '上传失败' return HttpResponse(json.dumps(ret)) # return JsonResponse(ret)
templates:
第一种上传文件或者图片: 这种的兼容性差 使用于一般的互联网公司仅仅支持谷歌这些浏览器
运用currentTarget获取你上传改变的input内的内容进行抓取改变的内容
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div style="position: relative;display: inline-block;height: 50px;min-width: 300px;overflow: hidden;"> <div style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;z-index: 1000;border: 1px dotted #9d9d9d;color: #9d9d9d;line-height: 50px;padding-left: 15px;"> <i class="fa fa-cloud-upload" aria-hidden="true"></i> <span>点击上传文件</span> </div> <input name="customer_excel" type="file" id="excelFile" style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;background-color: #333333;z-index: 1001;opacity: 0;filter:alpha(opacity=0);"> </div> <div> <input type="text" name="user"> <input type="submit" value="提交"> </div> </form> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> $(function () { $('#excelFile').change(function (e) { console.log(e); var fileName = e.currentTarget.files[0].name; {# currentTaget 是获取你的改变的标签的属性的事件 就是你的改变后的 这个标签内的名字#} {##} $(this).prev().find('span').text(fileName); }) }) </script> </body> </html>
第二种运用ajax来上传:兼容性也不好
运用:FormData,图片预览
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{#<!DOCTYPE html>#} {#<html lang="en">#} {#<head>#} {# <meta charset="UTF-8">#} {# <title>Title</title>#} {#</head>#} {#<body>#} {#就相当于你在你的图片上前面覆盖了一个内容 但是你的点击的提交让它隐藏你看着是点击了图片其实还是点击了这个input标签#} {#<div style = "height : 100px;width:100px; padding:2px; border:2px solid #dddddd; position:relative;" >#} {# <img style= "height:100%;width: 100%;border:0; ovreflow:hidden; border-radius:50%;" id="previewImg" src="" alt="">#} {# <input style= "top:0; left:0; right:0; bottom:0 ; opacity:0 ; position:absolute; z-index:102" id="avatarImg" name="avatar_img" type="file" class="img_file">#} {#</div>#} {##} {#<div>点击更换图片(<a href="#">撤销</a>)</div>#} {##} {##} {#<form method="post" enctype="multipart/form-data">#} {##} {# {% csrf_token %}#} {##} {##} {# <div>#} {# <input type="text" name="avatar" id="avatar">#} {# <input type="text" name="user">#} {# <input type="submit" value="提交">#} {##} {##} {# </div>#} {##} {##} {#</form>#} {#<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>#} {##} {# <script>#} {# $(function(){#} {# bindChangAvatar3();#} {# });#} {##} {# function bindChangAvatar3(){#} {# $('#avatarImg').change(function(){#} {# 当你的图片改变的时候就执行这个#} {# var file_obj = $(this)[0].files[0];#} {# 当你的jquery的操作的时候你取到下标为0的就是js的对象#} {# var form = new FormData();{# 生成一个formdata对象因为formdata是你在用ajax传递文件的时候必须要带着的 不然无法上传 #} {##} {# #} {##} {# form.append('img_upload',file_obj); {# 把file_objzhge对象添加进去 然后起个名字叫img_upload #} {##} {# $.ajax({#} {# url:'/form_data_upload/',#} {# type:'post',#} {# data:form,#} {##} {# processData:false,#} {# contentType:false, {# 这两个是告诉django不要给你的传递的字符串转化 格式#} {# success:function(arg){#} {# console.log(arg);#} {# $('#previewImg').attr('src','/'+arg);#} {# $('#avatar').val('/'+arg)#} {##} {##} {# }#} {# })#} {# })#} {# }#} {##} {# </script>#} {##} {##} {#</body>#} {#</html>#} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="height: 100px;width: 100px;padding: 2px;border: 1px solid #dddddd;position: relative;"> {# 设置你的 这个模块进行的父相子绝让你的input隐藏 并且让你点击的都是input#} <img style="height: 100%;width: 100%;border: 0;overflow: hidden;border-radius: 50%;" id="previewImg" src=""> <input style="top: 0;left: 0;right: 0;bottom: 0;opacity: 0;position: absolute;z-index: 102;" id="avatarImg" name="avatar_img" type="file" class="img-file"/> </div> <div>点击图片更换(<a href="#">撤销</a>)</div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div> <input type="text" name="avatar" id="avatar"> <input type="text" name="user"> <input type="submit" value="提交"> </div> </form> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> $(function () { bindChangeAvatar3(); }); function bindChangeAvatar3() { $('#avatarImg').change(function () { var file_obj = $(this)[0].files[0]; {#当你的jquery按照下标为0取到的都是js的对象#} var form = new FormData(); {#FormData是对你的传递的文件的时候必须要使用的#} form.append('img_upload', file_obj); $.ajax({ url: '/form_data_upload/', type:'POST', data: form, processData: false, // tell jQuery not to process the data {#告诉你的django你传递的字符串不要进行加工了 直接就是字符串样式的 因为django会对你的字符串进行加工#} contentType: false, // tell jQuery not to set contentType success: function (arg) { // 给img标签设置src属性,预览 console.log(arg); $('#previewImg').attr('src',"/"+arg); {#把你得到的样式进行放到img所要显示的样式#} $('#avatar').val("/"+arg); } }) }) } </script> </body> </html>
第三种:
伪造ajax iframe加上from来实现
iframe(兼容性最好)
1. iframe标签
可以修改src,且页面不刷新
2. form表单
提交表单数据,但刷新数据
这种的兼容性最好
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="height: 100px;width: 100px;padding: 2px;border: 1px solid #dddddd;position: relative;"> <iframe style="display: none;" id="ifr" name="fffff"></iframe> {# 运用你的iframe和from来实现一个伪ajax的操作 然后就能实现不刷新界面并且上传了#} <form method="POST" action="/upload_iframe/" enctype="multipart/form-data" target="fffff"> {# 想要是先这个伪造ajax的功能就必须要在form中设置一个target和#} {% csrf_token %} <img style="height: 100px;width: 100px;border: 0;overflow: hidden;border-radius: 50%;" id="prevImg" src="/static/imgs/default.png"> <input style="top: 0;left: 0;right: 0;bottom: 0;opacity: 0;position: absolute;z-index: 102;" id="avatar" name="avatar" type="file" class="img-file"/> </form> </div> <form method="post" action="/iframe_upload_img/"> {% csrf_token %} <input type="text" name="avatar" id="formAvatar" style="display: none"> <input type="text" name="user" placeholder="请输入用户名"> <input type="text" name="pwd" placeholder="请输入密码"> <input type="submit" value="提交"> </form> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> $(function () { bindChangeAvatar4(); }); function bindChangeAvatar4() { $('#avatar').change(function () { $(this).parent().submit(); $('#ifr')[0].onload = function (){ var iframeContents = $('#ifr')[0].contentWindow.document.body.innerText; iframeContents = JSON.parse(iframeContents); if (iframeContents.status) { $('#prevImg').attr('src', iframeContents.data); $('#formAvatar').val(iframeContents.data); } } }) } </script> </body> </html>