vue3 + element-plus 的 upload + axios + django 实现文件上传并保存功能

 更新时间:2024年01月10日 09:02:55   作者:卫龙吖  
这篇文章主要介绍了vue3 + element-plus 的 upload + axios + django 文件上传并保存,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

GPT4.0+Midjourney绘画+国内大模型 会员永久免费使用!
如果你想靠AI翻身,你先需要一个靠谱的工具!

之前在网上搜了好多教程,一直没有找到合适自己的,要么只有前端部分没有后端,要么就是写的不是很明白。所以还得靠自己摸索出来后,来此记录一下整个过程。

  • 其实就是不要用默认的 action,要手动实现上传方式 http-request,然后再传给后端进行各种操作了
    • 这里隐藏了文件展示列表
    • 展示了上传文件的个数
    • 文件去重上传
    • 也对上传文件的格式做了限制
    • 在点击创建的时候 progress 会随着上传进度动态变化

环境安装什么的就不讲了,直接上代码好吧,这个是样式图

这是vue3代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<template>
  <el-upload class="upload-demo form-item" v-model:file-list="fileList" drag multiple :http-request="httpRequest" :show-file-list="false" auto-upload="false" :accept=upload_accept>
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽 / 点击上传文件 ( zip, jpg, png ……)</div>
      <template #tip>
          <div class="el-upload__tip">已上传 {{ fileListLength }} 个文件</div>
      </template>
  </el-upload>
  <el-progress :percentage="progress.curr" :color="progress.color" />
  <el-button type="info" class="btn" @click="removeFile">清空文件</el-button>
  <el-button type="primary" class="btn" @click="create">创建</el-button>
</template>
 
<script setup lang="ts">
import { ref, watch } from "vue";
import http from "@/utils/axios/index";
import { UploadFilled } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
 
 
const public_elmsg_success = (msg: string) => {
  ElMessage({ type: 'success', duration: 1000, showClose: true, message: msg })
};
 
const public_elmsg_warning = (msg: string) => {
  ElMessage({ type: 'warning', duration: 1000, showClose: true, message: msg })
};
 
const public_elmsg_error = (msg: string) => {
  ElMessage({ type: 'error', duration: 1000, showClose: true, message: msg })
};
 
const upload_accept = ref(".JPG,.PNG,.JPEG,.PCD,.MP4,.AVI,.DAT,.DVR,.VCD,.MOV,.SVCD,.VOB,.DVD,.DVTR,.DVR,.BBC,.EVD,.FLV,.RMVB,.WMV,.MKV,.3GP,.ZIP"); // 限制了上传文件的格式 大写后缀
const upload_lower = ref(upload_accept.value.split(',').map((item: any) => item.toLowerCase())); // 限制上传文件的格式 小写后缀
const fileList: any = ref([]);
const fileList1: any = ref([]);
const fileListLength = ref(0);
 
const progress = ref({ "curr": 0, "color": "orange" })
 
 
watch(fileList1, (newVal, oldVal) => {
  console.log(newVal, oldVal)
  fileListLength.value = newVal.value;
  fileListLength.value = newVal.length;
}, { immediate: true, deep: true });
 
const httpRequest = (options: any) => {
  let nameList: Array<any> = [];
  fileList1.value.forEach((item: any) => {
      nameList.push(item.name);
  });
  const file_suffix = options.file.name.split(".");
  if (!upload_lower.value.includes(`.${file_suffix[file_suffix.length - 1]}`)) {
      public_elmsg_warning(`文件 ${options.file.name} 格式不正确`);
      return;
  }
  if (nameList.includes(options.file.name)) { }
  else {
      fileList1.value.push(options.file)
  }
  fileList.value = fileList1.value;
}
 
const removeFile = () => {
  fileList.value = [];
  fileList1.value = [];
  progress.value.curr = 0;
}
 
 
const create = () => {
  const formData = new FormData()
  fileList1.value.forEach((file: any) => {
      console.log(file)
      formData.append('files', file)
  })
 
  http.post("task/create/", formData, {
      headers: { "Content-Type": "multipart/form-data" }, onUploadProgress(progressEvent: any) {
          progress.value.curr = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          if (progress.value.curr == 100) { progress.value.color = 'green' }
          else { progress.value.color = 'orange' }
      },
  }).then((res: any) => {
      if (res.code == 0) {
          public_elmsg_success("任务创建成功")
      }
      else { public_elmsg_error(res.msg) }
  }
  );
}
</script>

v3版本的 djagno 代码 

1
2
3
4
5
6
7
8
9
10
11
12
from loguru import logger
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
    def create_task(request):
        files = request.FILES.getlist('files')
        for fit in files:
        logger.info(f"name: {fit.name} size: {round(fit.size/ 1024 / 1024 / 1024, 5)} G")
        # 保存文件
        #  with open(f"{os.sep.join(['.', fit['name']])}", mode="wb") as f:
        #         f.write(fit)
        return JsonResponse({"code": 0, "msg": "success"})

到此这篇关于vue3 + element-plus 的 upload + axios + django 文件上传并保存的文章就介绍到这了,更多相关vue3  文件上传并保存内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

蓄力AI

微信公众号搜索 “ 脚本之家 ” ,选择关注

程序猿的那些事、送书等活动等着你

原文链接:https://www.cnblogs.com/gwt805/p/17955473

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 reterry123@163.com 进行投诉反馈,一经查实,立即处理!

相关文章

  • vue openlayers实现台风轨迹示例详解

    vue openlayers实现台风轨迹示例详解

    这篇文章主要为大家介绍了vue openlayers实现台风轨迹示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-11-11
  • 如何使用Webpack优化Vue项目的打包流程

    如何使用Webpack优化Vue项目的打包流程

    在开发基于Vue.js的应用时,随着项目规模的扩大,单个文件的体积也会随之增长,特别是当涉及到大量的依赖库和复杂的业务逻辑时,本文将详细介绍如何使用Webpack来优化Vue项目的打包流程,需要的朋友可以参考下
    2024-09-09
  • 修改vue+webpack run build的路径方法

    修改vue+webpack run build的路径方法

    今天小编就为大家分享一篇修改vue+webpack run build的路径方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-09-09
  • 一文带你搞懂V8垃圾回收系统

    一文带你搞懂V8垃圾回收系统

    在V8中,JavaScript的内存空间分为栈(Stack)和堆(Heap)两部分,垃圾回收的基本思路是:查找内存中的所有变量,看哪些已经不再需要,然后释放这些变量所占用的内存,本文就给大家梳理一下V8垃圾回收系统,需要的朋友可以参考下
    2023-07-07
  • 详解vue高级特性

    详解vue高级特性

    这篇文章主要介绍了vue高级特性的相关知识,文中介绍非常细致,帮助大家更好的参考和学习,感兴趣的朋友可以了解下
    2020-06-06
  • Vue中通过Vue.extend动态创建实例的方法

    Vue中通过Vue.extend动态创建实例的方法

    这篇文章主要介绍了Vue中通过Vue.extend动态创建实例的方法,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-08-08
  • Vue实现预览文件(Word/Excel/PDF)功能的示例代码

    Vue实现预览文件(Word/Excel/PDF)功能的示例代码

    这篇文章主要为大家详细介绍了如何通过Vue实现预览文件(Word/Excel/PDF)的功能,文中的实现步骤讲解详细,需要的小伙伴可以参考一下
    2023-03-03
  • Vue中localStorage那些你不知道的知识分享

    Vue中localStorage那些你不知道的知识分享

    在Vue.js中, Vuex是一个强大的状态管理工具,而localStorage则是一种用于存储和获取本地数据的机制,虽然这两个东西都可以用来存储数据,但它们之间还是有很大的区别,本文就来简单说说吧
    2023-05-05
  • vue中vee validate表单校验的几种基本使用

    vue中vee validate表单校验的几种基本使用

    这篇文章主要介绍了vee-validate表单校验的基本使用,需要的朋友可以参考下
    2018-06-06
  • vue实现搜索功能

    vue实现搜索功能

    这篇文章主要为大家详细介绍了vue实现搜索功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-05-05

最新评论