首页 > 代码库 > .net 直接输出远程文件到浏览器和下载文件保存到本机

.net 直接输出远程文件到浏览器和下载文件保存到本机

 

利用了xmlhttp,实现代码比较简单具体实现如下:

首先bin文件引入,com->microsoft xml v3.0

具体代码如下:

protected void Button1_Click(object sender, EventArgs e)    {        string FileNames = "201406251824392435.pdf", ContentType = "";        string houzhui = FileNames.Substring(FileNames.LastIndexOf("."));        ContentType = checktype(FileNames);        string Url = "http://xxx.xxx.xxx.xxx:8089/upfile/wenku/" + FileNames;//域名或者ip地址        string StringFileName = Url.Substring(Url.LastIndexOf("/") + 1);        string StringFilePath = Request.PhysicalApplicationPath;        if (!StringFilePath.EndsWith("/")) StringFilePath += "/";        try        {            MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();            _xmlhttp.open("GET", Url, false, null, null);            _xmlhttp.send("");            if (_xmlhttp.readyState == 4)//数据接收完毕            {                if (_xmlhttp.status == 200)//是否返回正确数据                {                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("测试" + houzhui, System.Text.Encoding.UTF8));                    HttpContext.Current.Response.ContentType = ContentType;                    HttpContext.Current.Response.BinaryWrite((byte[])_xmlhttp.responseBody);//输出二进制到浏览器                    HttpContext.Current.Response.Flush();                    HttpContext.Current.Response.End();                }                else                { Response.Write("错误:" + _xmlhttp.statusText + " 未找到要下载的文件!"); }            }            else            {                Response.Write("错误:" + _xmlhttp.statusText + " 请求的http地址不对!");                Response.End();            }        }        catch (Exception ex)        {            Response.Write("错误:无法找到请求的资源!");            Response.End();        }    }

返回mime类型:

private static string checktype(string filename)    {        string ContentType;        string houzhui = filename.Substring(filename.LastIndexOf(".") + 1).Trim().ToLower();        switch (houzhui)        {            case ".asf":                ContentType = "video/x-ms-asf ";                break;            case ".avi":                ContentType = "video/avi ";                break;            case ".doc":                ContentType = "application/msword ";                break;            case ".zip":                ContentType = "application/zip ";                break;            case ".xls":                ContentType = "application/vnd.ms-excel ";                break;            case ".gif":                ContentType = "image/gif ";                break;            case ".jpg":                ContentType = "image/jpeg ";                break;            case "jpeg":                ContentType = "image/jpeg ";                break;            case ".wav":                ContentType = "audio/wav ";                break;            case ".mp3":                ContentType = "audio/mpeg3 ";                break;            case ".mpg":                ContentType = "video/mpeg ";                break;            case ".mepg":                ContentType = "video/mpeg ";                break;            case ".rtf":                ContentType = "application/rtf ";                break;            case ".html":                ContentType = "text/html ";                break;            case ".htm":                ContentType = "text/html ";                break;            case ".txt":                ContentType = "text/plain ";                break;            case ".pdf":                ContentType = "application/pdf";                break;            default:                ContentType = "application/octet-stream ";                break;        }        return ContentType;    }

 

 

 

下载文件并保存到本机:

  

 /// <summary>    /// 获取远程文件到本地    /// </summary>    /// <param name="url">远程文件地址</param>    /// <param name="path">本地路径</param>    private static void DownUrltoFile(string url, string path)    {        string Cookie = String.Empty;        String refer = url.Substring(0, url.LastIndexOf("/") + 1);        System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest;        req.AllowAutoRedirect = false;        req.Referer = refer;        req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";        System.Net.HttpWebResponse res = req.GetResponse() as System.Net.HttpWebResponse;        System.Net.WebHeaderCollection headers = res.Headers;        String newUrl = "";        if ((res.StatusCode == System.Net.HttpStatusCode.Found) ||          (res.StatusCode == System.Net.HttpStatusCode.Redirect) ||          (res.StatusCode == System.Net.HttpStatusCode.Moved) ||          (res.StatusCode == System.Net.HttpStatusCode.MovedPermanently))        {            newUrl = headers["Location"];            newUrl = newUrl.Trim();        }        if (headers["Set-Cookie"] != null)        {            Cookie = headers["Set-Cookie"];        }        res.Close();        req = null;        String fileName = newUrl.Substring(newUrl.LastIndexOf("/") + 1);        req = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest;        req.AllowAutoRedirect = true;        req.Referer = url;        req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";        res = req.GetResponse() as System.Net.HttpWebResponse;        System.IO.Stream stream = res.GetResponseStream();        byte[] buffer = new byte[32 * 1024];        int bytesProcessed = 0;        System.IO.FileStream fs = System.IO.File.Create(HttpContext.Current.Server.MapPath(path));        int bytesRead;        do        {            bytesRead = stream.Read(buffer, 0, buffer.Length);            fs.Write(buffer, 0, bytesRead);            bytesProcessed += bytesRead;        }        while (bytesRead > 0);        fs.Flush();        fs.Close();        res.Close();    }