MediaAPIController
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Web.Configuration;
using System.Web.Http;
namespace Fw.WebAPI.Controllers.FileAPI
{
[RoutePrefix("api/file/media")]
public class MediaAPIController : ApiController
{
#region Fields // This will be used in copying input stream to output stream.
public const int ReadStreamBufferSize = 1024 * 1024;
// We have a read-only dictionary for mapping file extensions and MIME names.
public static readonly IReadOnlyDictionary<string, string> MimeNames;
// We will discuss this later.
public static readonly IReadOnlyCollection<char> InvalidFileNameChars;
// Where are your videos located at? Change the value to any folder you want.
public static readonly string InitialDirectory; #endregion #region Constructors static MediaAPIController()
{
var mimeNames = new Dictionary<string, string>(); mimeNames.Add(".mp3", "audio/mpeg"); // List all supported media types;
mimeNames.Add(".mp4", "video/mp4");
mimeNames.Add(".ogg", "application/ogg");
mimeNames.Add(".ogv", "video/ogg");
mimeNames.Add(".oga", "audio/ogg");
mimeNames.Add(".wav", "audio/x-wav");
mimeNames.Add(".webm", "video/webm"); MimeNames = new ReadOnlyDictionary<string, string>(mimeNames); InvalidFileNameChars = Array.AsReadOnly(Path.GetInvalidFileNameChars());
InitialDirectory = WebConfigurationManager.AppSettings["InitialDirectory"];
} #endregion #region Actions
[Route("Play/{id}")]
[HttpGet]
public HttpResponseMessage Play(string id)
{
//从Gridfs中取文件流
IDFSHandle dsfHandle = new GridFSHandle();
Stream stream=dsfHandle.GetFile(id); // This can prevent some unnecessary accesses.
// These kind of file names won't be existing at all.
if (stream==null)
throw new HttpResponseException(HttpStatusCode.NotFound); long totalLength = stream.Length; RangeHeaderValue rangeHeader = base.Request.Headers.Range;
HttpResponseMessage response = new HttpResponseMessage(); response.Headers.AcceptRanges.Add("bytes"); // The request will be treated as normal request if there is no Range header.
if (rangeHeader == null || !rangeHeader.Ranges.Any())
{
response.StatusCode = HttpStatusCode.OK;
response.Content = new PushStreamContent((outputStream, httpContent, transpContext)
=>
{
using (outputStream) // Copy the file to output stream straightforward. try
{
stream.CopyTo(outputStream, ReadStreamBufferSize);
}
catch (Exception error)
{
Debug.WriteLine(error);
} }, GetMimeNameFromExt("mp4")); response.Content.Headers.ContentLength = totalLength;
return response;
} long start = 0, end = 0; // 1. If the unit is not 'bytes'.
// 2. If there are multiple ranges in header value.
// 3. If start or end position is greater than file length.
if (rangeHeader.Unit != "bytes" || rangeHeader.Ranges.Count > 1 ||
!TryReadRangeItem(rangeHeader.Ranges.First(), totalLength, out start, out end))
{
response.StatusCode = HttpStatusCode.RequestedRangeNotSatisfiable;
response.Content = new StreamContent(Stream.Null); // No content for this status.
response.Content.Headers.ContentRange = new ContentRangeHeaderValue(totalLength);
response.Content.Headers.ContentType = GetMimeNameFromExt("mp4"); return response;
} var contentRange = new ContentRangeHeaderValue(start, end, totalLength); // We are now ready to produce partial content.
response.StatusCode = HttpStatusCode.PartialContent;
response.Content = new PushStreamContent((outputStream, httpContent, transpContext)
=>
{
using (outputStream) // Copy the file to output stream in indicated range. CreatePartialContent(stream, outputStream, start, end); }, GetMimeNameFromExt("mp4")); response.Content.Headers.ContentLength = end - start + 1;
response.Content.Headers.ContentRange = contentRange; return response;
} #endregion #region Others private static bool AnyInvalidFileNameChars(string fileName)
{
return InvalidFileNameChars.Intersect(fileName).Any();
} private static MediaTypeHeaderValue GetMimeNameFromExt(string ext)
{
string value; if (MimeNames.TryGetValue(ext.ToLowerInvariant(), out value))
return new MediaTypeHeaderValue(value);
else
return new MediaTypeHeaderValue(MediaTypeNames.Application.Octet);
} private static bool TryReadRangeItem(RangeItemHeaderValue range, long contentLength,
out long start, out long end)
{
if (range.From != null)
{
start = range.From.Value;
if (range.To != null)
end = range.To.Value;
else
end = contentLength - 1;
}
else
{
end = contentLength - 1;
if (range.To != null)
start = contentLength - range.To.Value;
else
start = 0;
}
return (start < contentLength && end < contentLength);
} private static void CreatePartialContent(Stream inputStream, Stream outputStream,
long start, long end)
{
int count = 0;
long remainingBytes = end - start + 1;
long position = start;
byte[] buffer = new byte[ReadStreamBufferSize]; inputStream.Position = start;
do
{
try
{
if (remainingBytes > ReadStreamBufferSize)
count = inputStream.Read(buffer, 0, ReadStreamBufferSize);
else
count = inputStream.Read(buffer, 0, (int)remainingBytes);
outputStream.Write(buffer, 0, count);
}
catch (Exception error)
{
Debug.WriteLine(error);
break;
}
position = inputStream.Position;
remainingBytes = end - position + 1;
} while (position <= end);
} #endregion
}
}
MediaAPIController的更多相关文章
随机推荐
- COM组件双接口对象模型
模型如下: 这里COM对象一共实现了三个接口,IUnknown,IDispatch, Ixxx. 每个COM都必须实现IUnknown,不考虑在内的话共实现了IDispatch和自定义接口Ixxx两个 ...
- 【Linux】安装 PostgreSQL
参考: CSDN1:https://blog.csdn.net/ctwy291314/article/details/79900074 1.进入 PostgreSQL 官网的下载地址, 2.选择下面的 ...
- Flutter移动电商实战 --(33)列表页_子类和商品列表交互效果
主要实现点击小类下面的列表跟着切换 获取右侧下面的列表信息,即要传递大类的id也要传递小类的,所以需要把左侧的大类的id也要Provide化 可以看下网站上的接口说明: https://jspang. ...
- php学习之单例模式
<?php class Dog { private function __construct() { } //静态属性保存单例对象 static private $instance; stati ...
- DriverManager
1: 注册驱动 Class.forName("com.mysql.jdbc.Driver") ; static { try { java.sql.DriverManager.reg ...
- Python - pytesseract 机器视觉
机器视觉 - tesseract ( 验证码 ) 安装 Ubuntu sudo apt-get install tesseract-ocr Windows 下载安装包 添加环境变量(Path) :搜 ...
- 阶段5 3.微服务项目【学成在线】_day03 CMS页面管理开发_17-异常处理-可预知异常处理-异常处理测试
ResultCode有很多的实现类 cmsCode有很多类型的错误异常 pgeService内当CmsPage这个对象为空的时候,异常类型就可以抛出CmsCode里面的错误代码 if(cmsPage1 ...
- 阶段5 3.微服务项目【学成在线】_day02 CMS前端开发_11-webpack研究-npm和cnpm安装配置
node.js安装完成后,就自动安装了webpack. npm -v:查看npm安装的版本 当前安装目录默认的包 在node.js的目录下创建两个文件夹 这样路径就被修改成功了 cnpm npm in ...
- Spring事务管理3----声明式事务管理(1)
声明式事务管理(1)基于 基于 tx/aop 这种事务管理相比编程式事务管理来说对业务层基本没有改动,通过 TransactionProxyFactoryBean 创建业务层的代理,通过A ...
- 如何做一个项目v2.ppt
链接:https://pan.baidu.com/s/159GQsYK9BcQad3h1CyVUYg 提取码:ivcj 复制这段内容后打开百度网盘手机App,操作更方便哦