【Django后端分离】使用element-ui文件上传

【Django后端分离】使用element-ui文件上传,第1张

概述1:导入element <!-- 引入样式 --> <link rel="stylesheet" href="https://unpkg.com/ele

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=">            <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=" avatar"> <i v-else 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(,this.imageUrl) },beforeAvatarUpload(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error(上传头像图片只能是 JPG 格式!); } (!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 APIVIEwfrom SocIEtyPlat settingsfrom django.shortcuts render,redirect,httpResponsefrom Databases modelsfrom django.http JsonResponse 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(data') 用户名 username = str(request.data.get("username")) username = Wang" print(file_obj 判断是否存在文件夹 head_path = BASE_DIR + \media\{}\head".format(username).replace(" ","") 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] 图片后缀 图片后缀 png 储存路径 file_path = head_path + \{}".format(head." + head_suffix) file_path = file_path.replace(储存路径 C:\Users\user\Desktop\DownTest\media\username\head\head.png 上传图片 with open(file_path,1)">wb) as f: for chunk in file_obj.chunks(): f.write(chunk) message = {} message[code'] = 200 返回图片路径 back_path = \static\{}\head\{}'.format(username,1)">" + head_suffix).replace() message['] = back_path return JsonResponse(message)
@H_514_404@ 

总结

以上是内存溢出为你收集整理的【Django后端分离】使用element-ui文件上传全部内容,希望文章能够帮你解决【Django后端分离】使用element-ui文件上传所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1222816.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存