vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue3  文件上传并保存

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

作者:卫龙吖

这篇文章主要介绍了vue3 + element-plus 的 upload + axios + django 文件上传并保存,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

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

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

这是vue3代码

<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 代码 

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  文件上传并保存内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文