【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