TOP

[ASP.NET] 檔案下載時檔案名稱亂碼

原本使用的下載方式會造成 檔案下載時檔案名稱亂碼。
因此變更檔案下載的方式,並且將檔案名稱做UrlEncode。
Dim filePath As String = "c:/123檔案.txt"
Dim wc As WebClient = New WebClient()
Dim byteFile() As Byte = Nothing
byteFile = wc.DownloadData(filePath)
Response.AppendHeader("content-disposition", "attachment;filename=" + "123檔案名稱")
HttpContext.Current.Server.UrlEncode(docPhysicalName)
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(byteFile)
Response.End()

參考資料:
http://bob.logdown.com/posts/94996-aspnet-file-download

Response.WriteFile 檔案下載方式一
using System.IO;

string filePath = "C:/porn.jpg";
FileInfo file = new FileInfo(filePath);
Response.Clear()
Response.Buffer = false; 
Response.ContentType = "application/octet-stream"; // 指定檔案類型
Response.AddHeader("Content-Disposition","attachment;filename="+"porn.jpg"); // 設定檔名
// System.Web.HttpUtility.UrlEncode(newFileName, System.Text.Encoding.UTF8) 解決中文檔名亂碼
Response.AppendHeader("Content-Length", file.Length.ToString()); // 表頭加入檔案大小
Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
## System.Net.WebClient.DownloadData 檔案下載方式二

using System.Net;

WebClient wc = new WebClient();
byte[] byteFile = null;
string path = "C:/porn.jpg"; // 設定路徑
byteFile = wc.DownloadData(path);
string fileName = System.IO.Path.GetFileName(path); // 取得檔案名稱
Response.AppendHeader("content-disposition", "attachment;filename=" + "porn.jpg"); //設定檔名
// HttpContext.Current.Server.UrlEncode(fileName) 解決中文檔名亂碼
Response.ContentType = "application/octet-stream";  // 指定檔案類型   
Response.BinaryWrite(byteFile); // 內容轉出作檔案下載
Response.End();

亂碼處理的參考資料:
TOP

[CSS] Div CSS 浮水印(WaterMark)


<div style="overflow:hidden;height:96px;width:140px;margin: 0px auto;" >
   <asp:ImageButton ID="btnImage" runat="server" ImageUrl='<%# Eval("Image") %>' />                             <asp:ImageButton ID="btnWaterMark" style="position:relative; top: -70px;" runat="server"                              ImageUrl="~/images/gesplus/watermark-play.png"/>                                      
</div>

TOP

[Asp.Net] Download File from Remote Location to User Through Server

讀取遠端主機的錄影檔案,並且可以成功播放。

利用方法一的方式發生一種狀況是檔案有成功下載,但無法播放檔案。
利用方法二只能在檔案為本機的檔案時使用,因為是使用了 FileStream

為了可以取得遠端主機的錄影檔案,但又要可以成功播放檔案,
最後參考方法二的Context.Response.OutputStream方式才解決此問題。

差異點如下:

Context.Response.BinaryWrite(myStream.ToArray())
我現在是改為使用
Context.Response.OutputStream.Write(ByteBuffer, 0, count)


方法一:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//base.OnLoad(e);
string url = string.Empty;// Request.QueryString["DownloadUrl"];
if (url == null || url.Length == 0)
{
url = "http://img444.imageshack.us/img444/6228/initialgridsq7.jpg";
}

//Initialize the input stream
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
int bufferSize = 1;

//Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=download.jpg");
Response.AppendHeader("Content-Length", resp.ContentLength.ToString());
Response.ContentType = "application/download";

//Populate the output stream
byte[] ByteBuffer = new byte[bufferSize + 1];
MemoryStream ms = new MemoryStream(ByteBuffer, true);
Stream rs = req.GetResponse().GetResponseStream();
byte[] bytes = new byte[bufferSize + 1];
while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0)
{
Response.BinaryWrite(ms.ToArray());
Response.Flush();
}

//Cleanup
Response.End();
ms.Close();
ms.Dispose();
rs.Dispose();
ByteBuffer = null;
}
}


參考資料:http://www.dotnetwatch.com/Programmatically-Download-File-from-Remote-Locatio451_AR.aspx

方法二:

    private string _vsk_path_root = "";
    private string _vsk_path_files = "/contents/test/"; // directory path where mp4 videos reside
    //private bool _vsk_conf_limit_bandwidth = true;
    private bool _vsk_conf_allow_file_cache = false;
    // bandwidth settings
    //private int _vsk_bw_packet_size = 90; //set how many kilobytes will be sent per time interval
    //private float _vsk_bw_packet_internal = 0.3F; //set the time interval in which data packets will be sent in seconds.
    //private bool _vsk_conf_allow_dynamic_bandwith = true; //set to TRUE to control bandwidth externally via http.
    // incomming get variables
    //private string _vsk_get_bandwidth="bw";
    // domain restriction
    private bool _islimitdomain = false; // set to TRUE to limit access to the player
    private static string[] _allowed_domains = new string[] { "www.remix-video.com", "www.mediasoftpro.com" };
    private bool _isrestrictdomain = false; // set to TRUE to restrict access to the player.
    private static string[] _restricted_domains = new string[] { "www.sampledomain.com", "www.sampledomain2.com", "www.sampledomain3.com" };

    // points to server root
    public string VSK_PATH_ROOT
    {
        set { _vsk_path_root = value; }
        get { return _vsk_path_root; }
    }

    public string VSK_PATH_FILES
    {
        set { _vsk_path_files = value; }
        get { return _vsk_path_files; }
    }

    ////set to TRUE to use bandwidth limiting.
    //public bool VSK_CONF_LIMIT_BANDWIDTH
    //{
    //    set { _vsk_conf_limit_bandwidth = value;}
    //    get { return _vsk_conf_limit_bandwidth;}
    //}

    //set to FALSE to prohibit caching of video files.
    public bool VSK_CONF_ALLOW_FILE_CACHE
    {
        set { _vsk_conf_allow_file_cache = value; }
        get { return _vsk_conf_allow_file_cache; }
    }

    ////set how many kilobytes will be sent per time interval
    //public int VSK_BW_PACKET_SIZE
    //{
    //    set { _vsk_bw_packet_size = value;}
    //    get { return _vsk_bw_packet_size;}
    //}

    //// set the time interval in which data packets will be sent in seconds.
    //public float VSK_BW_PACKET_INTERVAL
    //{
    //    set { _vsk_bw_packet_internal = value;}
    //    get { return _vsk_bw_packet_internal;}
    //}

    ////set to TRUE to control bandwidth externally via http.
    //public bool VSK_CONF_ALLOW_DYNAMIC_BANDWIDTH
    //{
    //    set { _vsk_conf_allow_dynamic_bandwith = value;}
    //    get { return _vsk_conf_allow_dynamic_bandwith;}
    //}

    //public string VSK_GET_BANDWIDTH
    //{
    //    set { _vsk_get_bandwidth =value;}
    //    get { return _vsk_get_bandwidth;}
    //}

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            int i = 0;
            bool flag = false;
            // limit access of player to certain domains
            if (_islimitdomain)
            {
                if (context.Request.UrlReferrer == null)
                {
                    context.Response.Write("<b>ERROR:</b> Unknown Referrer.");
                    return;
                }
                StringCollection _list = new StringCollection();
                _list.AddRange(_allowed_domains);
                for (i = 0; i <= _list.Count - 1; i++)
                {
                    if (_list[i].Contains(context.Request.UrlReferrer.Host))
                        flag = true; // referrer host matched with list of allowed domains
                }
                if (!flag) // referrer host not matched
                {
                    context.Response.Write("<b>ERROR:</b> Access Denied.");

                    return;
                }
            }

            // restrict access of some domains to player
            if (_isrestrictdomain)
            {
                if (context.Request.UrlReferrer == null)
                {
                    context.Response.Write("<b>ERROR:</b> Unknown Referrer.");
                    return;
                }
                flag = false;
                StringCollection _list = new StringCollection();
                _list.AddRange(_restricted_domains);
                for (i = 0; i <= _list.Count - 1; i++)
                {
                    if (_list[i].Contains(context.Request.UrlReferrer.Host))
                        flag = true; // referrer host matched with list of restricted domains
                }
                if (flag) // referrer host matched with restricted domains
                {
                    context.Response.Write("<b>ERROR:</b> Access Restricted.");
                    return;
                }
            }

            // Security Check
            if (context.Request.Params["token"] == null)
            {
                //if (context.Request.Params["token"] != "kxdffxki")
                //{
                context.Response.Write("<b>ERROR:</b> Access Denied.");
                return;
                //}
            }


            int position;
            int length;
            // Check start parameter if present
            //string filename = Path.GetFileName(context.Request.FilePath);
            string filename = context.Request.Params["file"];
            string seekpos = context.Request.Params["start"];
            string user = context.Request.Params["token"]; // point token with author of video
            // assemble file path
            string rootpath = context.Server.MapPath(context.Request.ApplicationPath);
            // string file = rootpath + "" + this.VSK_PATH_FILES + "" + user + "/FLV/" + filename;
            string file = rootpath + "" + this.VSK_PATH_FILES + "" + filename;

            if (!File.Exists(file))
            {
                context.Response.Write("<b>ERROR:</b> vsk-mp4 could not find (" + filename + ") please check your settings.");
                return;
            }

            if (File.Exists(file) && filename.EndsWith(".mp4") && filename.Length > 2)
            {
                FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
                if (string.IsNullOrEmpty(seekpos))
                {
                    position = 0;
                    length = Convert.ToInt32(fs.Length);
                }
                else
                {
                    position = Convert.ToInt32(seekpos);
                    //length = Convert.ToInt32(fs.Length - position) + _header.Length;
                    length = Convert.ToInt32(fs.Length - position);
                }

                // Add HTTP header stuff: cache, content type and length      

                if (!this.VSK_CONF_ALLOW_FILE_CACHE)
                {
                    // session_cache_limiter("nocache");
                    // header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
                    // header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
                    // header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
                    //  header("Pragma: no-cache");
                }
                else
                {
                    //context.Response.Cache.SetCacheability(HttpCacheability.Public);
                    //context.Response.Cache.SetLastModified(DateTime.Now);
                }
                //context.Response.AppendHeader("Content-Type", "video/x-flv");
                context.Response.AppendHeader("Content-Type", "video/mp4");
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + "");
                context.Response.AppendHeader("Content-Length", length.ToString());

                // Read buffer and write stream to the response stream
                const int buffersize = 16384;
                byte[] buffer = new byte[buffersize];

                int count = fs.Read(buffer, 0, buffersize);
                while (count > 0)
                {
                    if (context.Response.IsClientConnected)
                    {
                        context.Response.OutputStream.Write(buffer, 0, count);
                        context.Response.Flush();
                        count = fs.Read(buffer, 0, buffersize);
                    }
                    else
                    {
                        count = -1;
                    }
                }
                fs.Close();


            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }

    }

參考資料:http://www.mediasoftpro.com/articles/asp.net-progressive-mp4-streaming.html


TOP

[ASP.Net] stream video content in asp.net

stream video content in asp.net 

方法一:
byte[] buffer = new byte[4096];

while(true) {
    int bytesRead = myStream.Read(buffer, 0, buffer.Length);
    if (bytesRead == 0) break;
    Response.OutputStream.Write(buffer, 0, bytesRead);
}

參考資料:
http://stackoverflow.com/questions/2687677/how-to-stream-video-content-in-asp-net

方法二:
VB.Net:

Using req As WebRequest = HttpWebRequest.Create("url here"), _
      stream As Stream = req.GetResponse().GetResponseStream()

End Using

C#:

WebRequest req = HttpWebRequest.Create("url here");
using (Stream stream = req.GetResponse().GetResponseStream() )
{

}

參考資料:
http://stackoverflow.com/questions/1223311/is-it-possible-to-read-from-a-url-into-a-system-io-stream-object