2013年10月22日 星期二

[ASP.NET MVC]輸入Youtube連結,產生預覽影片

前言

之前有做過一個需求跟FaceBook類似:將Youtube連結複製至TextArea,然後產生一個預覽影片,可以直接撥放,我們先直接看完成的結果:

 

youtube

 

分析

Youtube的小視窗,事實上就是一個iframe的標籤,可以指定他的長跟寬,連結(src)部分只要指定為http://www.youtube.com/embed/影片參數?rel=0即可瀏覽,而影片參數的部分其實就是每個影片會有一個Key值,這個Key值在每個影片連結後面可以看到v=xxxxxxx的值,只要將xxxxxxx的Value套至以上的影片參數就可以完成。

image

了解要怎麼做後,接下來就是技術的實現,本文使用JQuery Ajax + ASP.NET MVC實現。

1.前端使用Jquery,當Textbox失去焦點後,將輸入的內容(Youtube的URL)以Ajax丟至後端。

2.後端接收URL並解析所有參數,將參數V的value,回傳給前端。

3.前端接收V參數的Value,改變Iframe的值。

 

程式碼

 

前端

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('#txt_link').blur(function () {
$.ajax({
url: "@Url.Action("GetUrlArgument", "YoutubeSample")",
type: "POST",
data: { StrUrl: $('#txt_link').val() },
dataType: "html",
complete: function () {
},
success: function (data) {
if (data == "") {
$("#ifm_video").hide();
}
else {
$("#ifm_video").attr("src", "http://www.youtube.com/embed/" + data + "?rel=0");
$("#ifm_video").show();
}
},
Error: function () {
alert("發生錯誤");
}
});
});
});
</script>
</head>
<body>
<div>
@Html.Label("影片連結:")
@Html.TextBox("txt_link", "", new { style="width:200px" })
</div>
<div style="width: 800px;">
<iframe id="ifm_video" width="640" height="390" frameborder="0" allowfullscreen />
</div>

</body>
</html>
 

後端

/// <summary>解析URL參數</summary>
/// <param name="StrUrl"></param>
/// <returns></returns>
public ActionResult GetUrlArgument(string StrUrl)
{
if (StrUrl == "") return Content("");
string VideoKey = string.Empty;
try
{
Uri url = new Uri(StrUrl);
string queryString = url.Query; //取得所有參數
if (queryString != string.Empty)
{
NameValueCollection col = GetQueryString(queryString);
VideoKey = col["v"];
}
}
catch
{
VideoKey = string.Empty;
}

return Content(VideoKey);
}

/// <summary>
/// 解析所有參數
/// </summary>
/// <param name="queryString"></param>
/// <param name="encoding"></param>
/// <param name="isEncoded"></param>
/// <returns>回傳NameValueCollection</returns>
public static NameValueCollection GetQueryString(string queryString)
{
queryString = queryString.Replace("?", "");
NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrEmpty(queryString))
{
string[] Query = queryString.Split('&');
foreach (string pars in Query)
{
string[] pas = pars.Split('=');
result[pas[0]] = pas[1];
}
}
return result;
}

沒有留言:

張貼留言