Django后端分離 使用element-ui文件上傳方式
1:導(dǎo)入element
<!-- 引入樣式 --> <link rel='stylesheet' rel='external nofollow' > <!-- 引入組件庫 --> <script src='https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.min.js'></script> <!-- 引入Vue --> <script src='https://unpkg.com/element-ui/lib/index.js'></script>
2:前端文件
css:.avatar-uploader .el-upload { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; } .avatar-uploader .el-upload:hover { border-color: #409EFF; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; width: 178px; height: 178px; line-height: 178px; text-align: center; } .avatar { width: 178px; height: 178px; display: block; }html: {% comment %} 上傳圖片 {% endcomment %} <div id='profile'> <h1 >更新社團(tuán)封面</h1> <div style='text-align: center'> <el-upload:data= 'datas'// 攜帶的參數(shù):headers='headers' // 請(qǐng)求頭 name='image' {% comment %} 后端接收的參數(shù)名 {% endcomment %} action='/show/images/' {% comment %} 上傳路由地址 {% endcomment %} :show-file-list='false' :on-success='handleAvatarSuccess' {% comment %} 文件上傳成功時(shí)的鉤子 {% endcomment %} :before-upload='beforeAvatarUpload'> {% comment %} 上傳文件之前的鉤子,參數(shù)為上傳的文件 {% endcomment %}<img v-if='imageUrl' :src='http://www.aoyou183.cn/bcjs/imageUrl' class='avatar'><i v-else class='el-icon-plus avatar-uploader-icon'></i> </el-upload> </div> </div> {% comment %} 上傳圖片 {% endcomment %}# JS:<script> var Main = { data() { return {headers:{}, // 請(qǐng)求頭是個(gè)對(duì)象datas:{}, // 對(duì)象imageUrl: ’’ }; },create(){this.headers.authenticate = sessionStorage.getItem(’token’) // 設(shè)置請(qǐng)求頭帶tokenthis.datas.data = 'userHead' // 設(shè)置請(qǐng)求參數(shù)} methods: { handleAvatarSuccess(res, file) {this.imageUrl = URL.createObjectURL(file.raw);console.log('imageUrl',this.imageUrl) }, beforeAvatarUpload(file) {const isJPG = file.type === ’image/jpeg’;const isLt2M = file.size / 1024 / 1024 < 2;if (!isJPG) { this.$message.error(’上傳頭像圖片只能是 JPG 格式!’);}if (!isLt2M) { this.$message.error(’上傳頭像圖片大小不能超過 2MB!’);}return isJPG && isLt2M; } } } var Ctor = Vue.extend(Main) new Ctor().$mount(’#app’)</script>
3:后端文件
路由:# 預(yù)覽圖片url('show/images/$', add_image.Image.as_view()),py文件:from rest_framework.views import APIViewfrom SocietyPlat import settingsfrom django.shortcuts import render, redirect, HttpResponsefrom Databases import modelsfrom django.http import JsonResponseimport os# 獲取相對(duì)路徑BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))class Image(APIView): def post(self, request): # 接收文件 file_obj = request.FILES.get(’image’,None) style = requetst.data.get(’data’) # 用戶名 # username = str(request.data.get('username')) username = 'Wang' print('file_obj',file_obj.name) # 判斷是否存在文件夾 head_path = BASE_DIR + 'media{}head'.format(username).replace(' ','') print('head_path',head_path) # 如果沒有就創(chuàng)建文件路徑 if not os.path.exists(head_path): os.makedirs(head_path) # print('文件名',file_obj.name) # 文件名 name.png # # print('文件二進(jìn)制',file_obj.read()) # 文件二進(jìn)制 b’x89PNGrnx1anx00x00x00rIHDRx00x0 # # print('判斷文件> 2.5M',file_obj.multiple_chunks(chunk_size=None)) # 文件大小 False小于2.5M # # print('文件大小',file_obj.size) # 文件大小 12651 # # print('文件編碼',file_obj.charset) # None # # print('隨文件一起上傳的內(nèi)容類型標(biāo)題',file_obj.content_type) # image/png # # print('包含傳遞給content-type標(biāo)頭的額外參數(shù)的字典',file_obj.content_type_extra) # {} # # print('text/content-types提供的utf8字符集編碼',file_obj.charset) # None # # # 圖片后綴 head_suffix = file_obj.name.split('.')[1] print('圖片后綴',head_suffix) # 圖片后綴 png # 儲(chǔ)存路徑 file_path = head_path + '{}'.format('head.' + head_suffix) file_path = file_path.replace(' ','') print('儲(chǔ)存路徑', file_path) # C:UsersuserDesktopDownTestmediausernameheadhead.png # 上傳圖片 with open(file_path, ’wb’) as f: for chunk in file_obj.chunks():f.write(chunk) message = {} message[’code’] = 200 # 返回圖片路徑 back_path = ’static{}head{}’.format(username,'head.' + head_suffix).replace(' ','') message[’image’] = back_path return JsonResponse(message)
補(bǔ)充知識(shí):django后臺(tái)接口處理element-ui的el-upload組件form data類型數(shù)據(jù)
對(duì)于向我這樣一只前端和后端的雙咸魚來說寫一個(gè)不了解的接口實(shí)在是太難受了,前端不知道在哪找數(shù)據(jù),后端又不知道處理什么樣的數(shù)據(jù)。
現(xiàn)在有這樣一個(gè)需求,我需要使用element-ui中的el-upload組件完成一個(gè)上傳文件的功能。但是不知道是不是因?yàn)槲覜]有發(fā)現(xiàn),我翻遍了官網(wǎng)都沒有找到這個(gè)組件點(diǎn)擊上傳以后發(fā)的是什么樣的數(shù)據(jù)請(qǐng)求。
終于我好像突然想起來瀏覽器的開發(fā)者工具可以查看發(fā)出的請(qǐng)求
于是我們可以寫這么一個(gè)組件來一探究竟:
點(diǎn)擊上傳到服務(wù)器以后前臺(tái)就會(huì)發(fā)出請(qǐng)求,我們就可以使用devtool看具體的請(qǐng)求頭等等數(shù)據(jù),具體位置在這里:
點(diǎn)擊這個(gè)upload,找一找,我們就會(huì)發(fā)現(xiàn)最下面有一個(gè)file
這應(yīng)該就是我們要上傳的文件。可以看見它是以form data的形式上傳的。
所以我們就可以寫對(duì)應(yīng)的后端接口了。
這里給一個(gè)接口的demo
def writeFile(filePath, file): with open(filePath, 'wb') as f: if file.multiple_chunks(): for content in file.chunks():f.write(content) else: data=file.read() ###.decode(’utf-8’) f.write(data)def uploadFile(request): if request.method == 'POST': fileDict = request.FILES.items() # 獲取上傳的文件,如果沒有文件,則默認(rèn)為None if not fileDict: return JsonResponse({’msg’: ’no file upload’}) for (k, v) in fileDict: print('dic[%s]=%s' %(k,v)) fileData = request.FILES.getlist(k) for file in fileData:fileName = file._get_name()filePath = os.path.join(settings.TEMP_FILE_PATH, fileName)print(’filepath = [%s]’%filePath)try: writeFile(filePath, file)except: return JsonResponse({’msg’: ’file write failed’}) return JsonResponse({’msg’: ’success’})
另外想要在前端獲取后端返回的請(qǐng)求的話可以使用on-success、on-error、on-exceed這幾個(gè)鉤子函數(shù),具體可以在element ui的官網(wǎng)找到
以上這篇Django后端分離 使用element-ui文件上傳方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python結(jié)合百度語音識(shí)別實(shí)現(xiàn)實(shí)時(shí)翻譯軟件的實(shí)現(xiàn)2. 教你JS更簡單的獲取表單中數(shù)據(jù)(formdata)3. JavaScript設(shè)計(jì)模式之策略模式實(shí)現(xiàn)原理詳解4. Python基于QQ郵箱實(shí)現(xiàn)SSL發(fā)送5. 測(cè)試模式 - XSL教程 - 56. JAVA抽象類及接口使用方法解析7. 如何通過vscode運(yùn)行調(diào)試javascript代碼8. python如何寫個(gè)俄羅斯方塊9. 《CSS3實(shí)戰(zhàn)》筆記--漸變?cè)O(shè)計(jì)(一)10. python b站視頻下載的五種版本
