当前位置: 首页 > news >正文

uniapp访问django目录中的图片和视频,2025[最新]中间件访问方式

 新建中间件,

middleware.py

匹配,以/cover_image/ 开头的图片

匹配以/episode_video/ 开头的视频

imageSrc: 'http://192.168.110.148:8000/cover_image/12345/1738760890657_mmexport1738154397386.jpg',
videoSrc: 'http://192.168.110.148:8000/episode_video/12345/compress_video_99945997.mp4'

import os
import re
import mimetypes
from django.conf import settings
from django.http import StreamingHttpResponse, Http404, HttpResponseclass VideoStreamMiddleware:"""视频流中间件"""def __init__(self, get_response):self.get_response = get_responsedef __call__(self, request):# 检查请求的路径是否以 '/episode_video/' 开头if request.path.startswith('/episode_video/'):user_id = request.path.split('/')[2]print("request.path----------", user_id)return self.stream_video(request, user_id)# 检查请求的路径是否以 '/cover_image/' 开头if request.path.startswith('/cover_image/'):user_id = request.path.split('/')[2]print("request.path----------", user_id)return self.stream_image(request,user_id)response = self.get_response(request)return responsedef stream_video(self, request, user_id):filename = request.path.split('/')[-1]  # 从路径中提取文件名path = os.path.join(settings.MEDIA_ROOT, 'episode_video/' + user_id, filename)  # 视频文件存储路径print("path是,,,,,,", path)if not os.path.exists(path):raise Http404("File not found")range_header = request.META.get('HTTP_RANGE', '').strip()range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I)range_match = range_re.match(range_header)size = os.path.getsize(path)content_type, _ = mimetypes.guess_type(path)content_type = content_type or 'application/octet-stream'if range_match:first_byte, last_byte = range_match.groups()first_byte = int(first_byte) if first_byte else 0last_byte = first_byte + 1024 * 1024 * 8  # 默认8MB每片if last_byte >= size:last_byte = size - 1length = last_byte - first_byte + 1resp = StreamingHttpResponse(self.file_iterator(path, offset=first_byte, length=length), status=206,content_type=content_type)resp['Content-Length'] = str(length)resp['Content-Range'] = f'bytes {first_byte}-{last_byte}/{size}'else:# 返回整个文件resp = StreamingHttpResponse(self.file_iterator(path), content_type=content_type)resp['Content-Length'] = str(size)resp['Accept-Ranges'] = 'bytes'return respdef stream_image(self, request,user_id):filename = request.path.split('/')[-1]  # 从路径中提取文件名path = os.path.join(settings.MEDIA_ROOT, 'cover_image/'+user_id, filename)  # 图片文件存储路径print("image path是,,,,,,", path)if not os.path.exists(path):raise Http404("File not found")content_type, _ = mimetypes.guess_type(path)content_type = content_type or 'application/octet-stream'# 返回图片文件with open(path, 'rb') as f:response = HttpResponse(f.read(), content_type=content_type)response['Content-Length'] = os.path.getsize(path)return responsedef file_iterator(self, file_name, chunk_size=8192, offset=0, length=None):"""文件迭代器,按块读取文件"""with open(file_name, "rb") as f:f.seek(offset, os.SEEK_SET)remaining = lengthwhile True:bytes_length = chunk_size if remaining is None else min(remaining, chunk_size)data = f.read(bytes_length)if not data:breakif remaining:remaining -= len(data)yield data

不要忘记在settings.py中注册中间件

'user.middleware.VideoStreamMiddleware'

uniapp中 新建界面 访问

<template><view class="container"><text class="title">展示图片和视频</text><!-- 展示图片 --><image :src="imageSrc" mode="aspectFit"></image><video :src="videoSrc" controls></video></view>
</template><script>
export default {data() {return {imageSrc: 'http://192.168.110.148:8000/cover_image/12345/1738760890657_mmexport1738154397386.jpg',videoSrc: 'http://192.168.110.148:8000/episode_video/12345/compress_video_99945997.mp4'};}
};
</script><style></style>

http://www.lryc.cn/news/534320.html

相关文章:

  • RuoYi-Vue-Oracle的oracle driver驱动配置问题ojdbc8-12.2.0.1.jar的解决
  • python脚本实现windows电脑内存监控内存清理(类似rammap清空工作集功能)
  • 【狂热算法篇】并查集:探秘图论中的 “连通神器”,解锁动态连通性的神秘力量
  • SpringBoot中实现动态数据源切换
  • 数据结构及排序算法
  • Python基础-元组tuple的学习
  • 【手写公式识别】MEMix: Improving HMER with Diverse Formula Structure Augmentation 论文阅读
  • 使用deepseek写一个飞机大战游戏
  • 用Kibana实现Elasticsearch索引的增删改查:实战指南
  • C# 封送和远程编程介绍
  • MybatisPlus较全常用复杂查询引例(limit、orderby、groupby、having、like...)
  • 02.07 TCP服务器与客户端的搭建
  • Jenkins数据备份到windows FTP服务器
  • 【R语言】卡方检验
  • ASP.NET Core托管服务
  • HarmonyOS 5.0应用开发——全局自定义弹出框openCustomDialog
  • 如何在C++ QT 程序中集成cef3开源浏览器组件去显示网页?
  • 深入讲解MyBatis
  • 使用matlab 对传递函数分析bode图和阶跃函数
  • 2025牛客寒假算法基础集训营5(补题)
  • FaceFusion如何设置公开链接和端口
  • 神经网络常见激活函数 6-RReLU函数
  • 计算机网络面经
  • Qt:常用控件
  • 算法设计-找第二大数(C++)
  • 【C++高并发服务器WebServer】-14:Select详解及实现
  • redis项目
  • Spring统一修改RequestBody
  • NCV4275CDT50RKG 车规级LDO线性电压调节器芯片——专为新能源汽车设计的高可靠性电源解决方案
  • 前端开发架构师Prompt指令的最佳实践