天天看點

【vue】element-ui 上傳檔案

文章目錄

    • 前端
    • 背景

前端

  • axios api設定
export function project_file_add(data) {
  return request({
    url: '/api/project-file',
    method: 'POST',
    data
  })
}
           
  • 自動上傳

    vue代碼

<template>
  <div>
    <el-upload
      drag
      multiple
      :before-upload="beforeAvatarUpload"
      :action="''"
      :data="file"
      :http-request="upload"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">
        将檔案拖到此處,或
        <em>點選上傳</em>
      </div>
      <div slot="tip" class="el-upload__tip">隻能上傳jpg/png檔案,且不超過500kb</div>
    </el-upload>
  </div>
</template>

<script>
import { project_file_add } from '@/api/project'

export default {
  name: 'Demo',
  data() {
    return {
      file: {
        project: '1'
      },
      uploadurl: ''
    }
  },
  methods: {
    upload(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      formData.append('project', 1)
      project_file_add(formData).then(_ => {
        this.$message({
          message: '檔案上傳成功',
          type: 'success',
          showClose: true
        })
      }
      ).catch(_ => {
        this.$message({
          message: '檔案上傳失敗',
          type: 'error',
          showClose: true
        })
      }
      )
    },
    beforeAvatarUpload(file) {
      return true
    },
    submitUpload() {
      this.$refs.upload.submit()
    }
  }
}
</script>

<style scoped>

</style>
           
  • 手動上傳

    :auto-upload=“false” 手動上傳一定要寫明這個屬性為false

<template>
  <div>
    <el-upload
      ref="upload"
      drag
      multiple
      :auto-upload="false"
      :before-upload="beforeAvatarUpload"
      :action="''"
      :data="file"
      :http-request="upload"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">
        将檔案拖到此處,或
        <em>點選上傳</em>
      </div>
      <div slot="tip" class="el-upload__tip">隻能上傳jpg/png檔案,且不超過500kb</div>
    </el-upload>
    <el-button style="margin-left: 250px;" size="small" type="success" @click="submitUpload">确認上傳</el-button>
  </div>
</template>

<script>
import { project_file_add } from '@/api/project'

export default {
  name: 'Demo',
  data() {
    return {
      file: {
        project: '1'
      },
      uploadurl: ''
    }
  },
  methods: {
    upload(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      formData.append('project', 1)
      project_file_add(formData).then(_ => {
        this.$message({
          message: '檔案上傳成功',
          type: 'success',
          showClose: true
        })
      }
      ).catch(_ => {
        this.$message({
          message: '檔案上傳失敗',
          type: 'error',
          showClose: true
        })
      }
      )
    },
    beforeAvatarUpload(file) {
      return true
    },
    submitUpload() {
      this.$refs.upload.submit()
    }
  }
}
</script>

<style scoped>

</style>
           

背景

  • model
import os

from django.db import models

from python_vfeng_ICDaily_django import settings
from utils.base_mysql_model import BaseMysqlModel


def file_directory_path(instance, filename):
    return os.path.join('uploads', 'project', str(instance.project.id), filename)


class ProjectFileModel(BaseMysqlModel):
    file = models.FileField(upload_to=file_directory_path, null=False, blank=False, verbose_name='檔案路徑')
    md5 = models.CharField(max_length=36, null=False, blank=False, verbose_name="MD5")
    project = models.ForeignKey('ProjectModel', on_delete=models.CASCADE, related_name='files', null=False, blank=False,
                                verbose_name="項目類型")
    uploader = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, verbose_name='上傳者')

    class Meta:
        verbose_name = '項目附件'
        verbose_name_plural = verbose_name
           
  • view set
from rest_framework import permissions, filters

from project.filters import ProjectFileFilter
from project.models import ProjectFileModel
from project.serializer import ProjectFileSerializer
from utils.api_page_number_pagination import ApiPageNumberPagination
from utils.base_mysql_model_view_set import BaseMysqlModelViewSet


class ProjectFileViewSet(BaseMysqlModelViewSet):
    queryset = ProjectFileModel.objects.all().order_by('-create_time')
    serializer_class = ProjectFileSerializer
    filter_class = ProjectFileFilter

    # permission_classes = (permissions.AllowAny,)
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = ApiPageNumberPagination

    def create(self, request, *args, **kwargs):
        request.data['md5'] = 'b46a11d5aa530800d8b786527e6a6b5d'  # hashlib.md5(request.FILES['file']).hexdigest()
        request.data['uploader'] = request.user.id
        return super().create(request, *args, **kwargs)
           
  • Serializer
class ProjectFileSerializer(serializers.ModelSerializer):
    uploader_name = serializers.CharField(source='uploader.cn', read_only=True)
    file_name = serializers.SerializerMethodField()
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)

    class Meta:
        model = ProjectFileModel
        fields = '__all__'

    def get_file_name(self, instance):
        split_str = '/' + str(instance.project.id) + '/'
        return instance.file.name.split(split_str)[-1]
           

繼續閱讀