【UNIAPP】上传视频,进度条的前台与后端


#  UNIAPP 页面

<template> <view> <!-- 选择框 --> <view style="display: flex;flex-direction: row;justify-content: center;margin-top: 40px;" @click="select"> <u-circle-progress active-color="#2979ff" percent="100" duration="100"> <view class="u-progress-content"> <image src="@/static/up.png" style="width: 40px;height: 40px;"></image> </view> </u-circle-progress> </view> <!-- 进度条 --> <view class="uni-padding-wrap uni-common-mt" style="margin-top: 30px;" > <view class="progress-box"> <progress :percent="percent" stroke-width="20" show-info border-radius="20" /> </view> </view> <!-- 表单 --> <view style="margin-top: 40px;"> <view class="cu-form-group"> <view class="title">视频标题</view> <input placeholder="请输入标题" name="input" v-model="title"></input> <text class='cuIcon-title text-orange' style="font-size: 25px;"></text> </view> <view class="cu-form-group margin-top"> <view class="title">视频分类</view> <picker @change="PickerChange" :value="index" :range="picker"> <view class="picker"> {{index>-1?picker[index]:'请选择分类'}} </view> </picker> </view> </view> <!-- 下单按钮 --> <view class="padding flex flex-direction" style="margin-top: 20px;"> <button class="cu-btn bg-blue margin-tb-sm lg" @click="release_task">发布</button> </view> <!-- 提醒 --> <view> <u-toast ref="uToast" /> </view> <!-- 上传成功 --> </view> </template> <script> /* 导入 */ import config from "@/common/config.js"; var _self; export default { data() { return { /* 上传LOGO */ src: "/static/up.png", /* 视频文件 */ file: "", title: "", /* 进度条 */ percent: 0, jianjian: 0, loading: false, disabled: false, picker: ['音乐', '生活', '影视', '舞蹈', '游戏', '美食', ], index: -1, } }, computed: { }, onLoad() { }, methods: { /* 提示 */ uToast() { uni.showModal({ title: '消息提示', content: '上传成功', showCancel: false, confirmText: "我知道了", success: function(res) { } }); }, /* 选择视频 */ select() { _self = this; uni.chooseVideo({ count: 1, maxDuration: 60, sourceType: ['camera', 'album'], //从选择 success: function(res) { // 临时文件 _self.src = res.tempFilePath }, error: function(e) { console.log(e); } }); }, /* 品牌选择 */ PickerChange(e) { this.index = e.detail.value }, /* 上传 */ release_task() { _self = this; // const tempFilePaths = res.tempFilePaths; const uploadTask = uni.uploadFile({ // url: 'https://demo.hcoder.net/index.php?c=uperTest', url: config.ipConfig + '/api/upload/video', filePath: _self.src, name: 'file', formData: { 'username_id': 1 }, success: function(uploadFileRes) { _self.uToast() } }); uploadTask.onProgressUpdate(function(res) { _self.percent = res.progress; }); } }, } </script> <style lang="scss" scoped> .u-progress-content { display: flex; align-items: center; justify-content: center; } .u-progress-dot { width: 16rpx; height: 16rpx; border-radius: 50%; background-color: #fb9126; } .u-progress-info { font-size: 28rpx; padding-left: 16rpx; letter-spacing: 2rpx } </style>

 

 

 

 

后端部分:
# upload_files.py 储存文件

"""
    上传文件  UploadFiles(用户名,功能名,图片对象,编号ID)
"""

import traceback
import os

from utils import datamd5
# 获取相对路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))



def UploadVideo(username,function,files):

    try:

        # 上传路径
        dir_path = BASE_DIR + "/media/{}/{}/".format(function,username)

        # 后缀名
        head_suffix = files.name.split(".")[1]

        # 如果没有这个路径就创建
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        path=''

        # 为了避免覆盖 对名字进行加密
        file_name = datamd5.md5(files.name) + "." + head_suffix

        with open(dir_path + file_name, 'wb') as dest:
            # 获取路径 这里少了个media
            path = path + '/{}/{}/'.format(function,username) + file_name

            for chunk in files.chunks():
                dest.write(chunk)

        return True,path

    except:

        # print(traceback.format_exc())
        return False,None






# 上传记录与数据库储存

# -*- coding: UTF-8 -*-
import os
import traceback

from rest_framework.views import APIView
from database import models
from django.http import JsonResponse
import datetime
import time
from utils import upload_files


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

class ReleaseVideo(APIView):

    def post(self,request):

        message = {}

        try:

            # 对象
            file_obj = request.FILES.get('file', None)

            username_id = request.data.get("username_id")

            title = request.data.get("title")

            style = int(request.data.get("style")) + 1

            function = 'upload_video'

            # 上传函数执行
            status,path = upload_files.UploadVideo(username_id, function, file_obj)

            if status == False:
                message["code"] = 10041
                message["message"] = "上传失败"
                return JsonResponse(message)


            # 数据库操作
            obj = models.List.objects.create(title=title,user_id=username_id,price=0,style_id=style)
            models.ListDetail.objects.create(list_id=obj.pk,address=path)

            message["code"] = 200
            message["message"] = "发布成功"
            return JsonResponse(message)

        except:
            print(traceback.format_exc())

            message["code"] = 10044
            message["message"] = "发布失败"
            return JsonResponse(message)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM