上傳圖片或者文件
阿新 • • 發佈:2018-07-19
內容 [1] The esp als flow 你在 ng- type
以後絕對會用到 使用ajax上傳文件或者圖片
urls:
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/urls‘,views.upload_file), #上傳文件 path(‘iframe_upload_img/‘,views.iframe_upload_img), path(‘upload_iframe/‘, views.upload_iframe), ]
views:
from django.shortcuts import render,redirect,HttpResponse import os import uuid def upload_img(request): ‘‘‘ 上傳圖片 :param request: :return:views‘‘‘ 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內的內容進行抓取改變的內容
<!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,圖片預覽
{#<!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="" >#} {# <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>第二種 img
第三種:
偽造ajax iframe加上from來實現
iframe(兼容性最好)
1. iframe標簽
可以修改src,且頁面不刷新
2. form表單
提交表單數據,但刷新數據
這種的兼容性最好
<!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>偽造ajax
上傳圖片或者文件