MP4视频下载实现简介

来源:本站原创 点击数: 发布时间:2026年04月22日

MP4 视频下载实现

MP4 文件默认会被浏览器识别为“可在线播放媒体”,因此直接访问通常是:

在线播放

而不是:

下载文件

要实现“点击下载按钮时下载,而不是播放”,核心是:

返回 Content-Disposition: attachment

一、Nginx 实现


1️⃣ 虚拟目录方式(推荐)

配置

server {
   listen 80;
   server_name yourdomain.com;

   # 播放路径(不变)
   location /upload/ {
       root /data/www;   # 实际路径:/data/www/upload/
   }

   # 下载路径(关键)
   location /download/ {
       alias /data/www/upload/;

       add_header Content-Disposition 'attachment';
       add_header Content-Type application/octet-stream;
   }
}

前端使用

<!-- 播放 -->
<video controls width="600">
   <source src="/upload/main/contentmanage/video/2026/03/30/22.mp4" type="video/mp4">
</video>

<!-- 下载 -->
<a href="/download/main/contentmanage/video/2026/03/30/22.mp4">
   下载视频
</a>

2️⃣ 参数控制方式

配置

location /upload/ {
   root /data/www;

   # 如果带 ?download=1 才触发下载
   if ($arg_download = "1") {
       add_header Content-Disposition 'attachment';
       add_header Content-Type application/octet-stream;
   }
}

前端

<a href="/upload/main/contentmanage/video/2026/03/30/22.mp4?download=1">
   下载视频
</a>

⚠️ Nginx注意

  • aliasroot 不要混用错误

  • if 虽然可用,但复杂场景建议用 map 优化(这里简单用法OK)


二、IIS 实现


1️⃣ 虚拟目录方式(最推荐)

步骤

① 添加虚拟目录

名称物理路径
uploadD:\www\upload
downloadD:\www\upload

② 在 /download 目录放 web.config

<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Content-Disposition" value="attachment" />
       <add name="Content-Type" value="application/octet-stream" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

前端

<!-- 播放 -->
<video controls width="600">
 <source src="/upload/main/contentmanage/video/2026/03/30/22.mp4" type="video/mp4">
</video>

<!-- 下载 -->
<a href="/download/main/contentmanage/video/2026/03/30/22.mp4">
 下载视频
</a>

2️⃣ 参数控制方式(URL Rewrite)

前提

需要安装:
👉 IIS URL Rewrite 模块


web.config 配置

<configuration>
 <system.webServer>
   <rewrite>
     <outboundRules>
       <rule name="Download MP4 by Query">
         <match serverVariable="RESPONSE_Content-Disposition" pattern=".*" />
         <conditions>
           <add input="{QUERY_STRING}" pattern="download=1" />
         </conditions>
         <action type="Rewrite" value="attachment" />
       </rule>
     </outboundRules>
   </rewrite>
 </system.webServer>
</configuration>

前端

<a href="/upload/main/contentmanage/video/2026/03/30/22.mp4?download=1">
 下载视频
</a>