1:導入element
<!-- 引入樣式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <!-- 引入組件庫 --> <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 style="text-align: center" >更新社團封面</h1> <div id="app" style="text-align: center"> <el-upload
:data= "datas" // 攜帶的參數
:headers="headers" // 請求頭 name="image" {% comment %} 后端接收的參數名 {% endcomment %} class="avatar-uploader" action="/show/images/" {% comment %} 上傳路由地址 {% endcomment %} :show-file-list="false" :on-success="handleAvatarSuccess" {% comment %} 文件上傳成功時的鈎子 {% endcomment %} :before-upload="beforeAvatarUpload"> {% comment %} 上傳文件之前的鈎子,參數為上傳的文件 {% endcomment %} <img v-if="imageUrl" :src="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:{}, // 請求頭是個對象
datas:{}, // 對象 imageUrl: '' }; },
create(){
this.headers.authenticate = sessionStorage.getItem('token') // 設置請求頭帶token
this.datas.data = "userHead" // 設置請求參數
}
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:后端文件
路由:
# 預覽圖片
url("show/images/$", add_image.Image.as_view()),
py文件:
from rest_framework.views import APIView from SocietyPlat import settings from django.shortcuts import render, redirect, HttpResponse from Databases import models from django.http import JsonResponse import os # 獲取相對路徑 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) # 如果沒有就創建文件路徑 if not os.path.exists(head_path): os.makedirs(head_path) # print("文件名",file_obj.name) # 文件名 name.png # # print("文件二進制",file_obj.read()) # 文件二進制 b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x0 # # print("判斷文件> 2.5M",file_obj.multiple_chunks(chunk_size=None)) # 文件大小 False小於2.5M # # print("文件大小",file_obj.size) # 文件大小 12651 # # print("文件編碼",file_obj.charset) # None # # print("隨文件一起上傳的內容類型標題",file_obj.content_type) # image/png # # print("包含傳遞給content-type標頭的額外參數的字典",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 # 儲存路徑 file_path = head_path + "\\{}".format("head." + head_suffix) file_path = file_path.replace(" ","") print("儲存路徑", file_path) # C:\Users\user\Desktop\DownTest\media\username\head\head.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)