導航:首頁 > 版本升級 > nethttprequest下載文件

nethttprequest下載文件

發布時間:2023-05-16 08:00:12

A. ASP.NET 中,實現download下載,彈出打開和保存對話框,不限制文件大小,跪求實現代碼,謝謝了

思路很簡單,讀取伺服器文件路徑,然後再保存數據流,下面是實現代碼:
(ps:因為要上班,來不及寫很多注釋,關鍵的地方加了幾句注釋哈)

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using YTLib.Basic;
using YTLib.YTDBC;
using System.IO;
using System.Threading;
namespace siteadmin.admin
{
public partial class downfile : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
string strSQL = "";

YTNDBObject dbo = new YTNDBObject();
dbo.DataName = "Main";
Page.EnableViewState = false;
if(!IsPostBack)
{
string sid=Request["id"];
if(!YTLib.publicOP.IsNumString(sid)||sid==null)
sid="0";
strSQL = "select * from FileSource where ID=@ID";
dbo.PrepareCommand(strSQL);
dbo.SetCmdIntValue("@ID",int.Parse(sid));
DataTable dt=dbo.QueryData().Tables[0];
string sourceName = (string)dt.Rows[0]["FilePath"];
sourceName.Trim();//消除空格
string filesnames = sourceName.Substring(7, sourceName.Length - 8);
int index= sourceName.LastIndexOf(".");
string extend = sourceName.Substring(index+1);//擴展名
string fullPath = "~/uploaded/" + sourceName;
fullPath = Server.MapPath(fullPath);
//讀出該資源的下載次數
int downloadtimes = 0;

downloadtimes = int.Parse(dt.Rows[0]["downloadCounts"].ToString());

Page.Response.Clear();
bool success = ResponseFile(Page.Request, Page.Response, filesnames, fullPath, 1024000);
if (!success) Response.Write("<script language=\"javascript\">alert(\"Download file error\");window.location.href=\"../Download.aspx\"</script>");
else
{
//記錄下載次數
downloadtimes++;
string sqlStr = "update FileSource set downloadCounts=" + downloadtimes + " where ID=@IID";
dbo.PrepareCommand(sqlStr);
dbo.SetCmdIntValue("@IID",int.Parse(sid));
dbo.ExecuteNoQuery();
}
Response.Write("<script language=\"javascript\">window.location.href=\"../Download.aspx\"</script>");
}
}
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;//不緩沖
long fileLength = myFile.Length;
long startBytes = 0;
double pack = 10240;
//10K bytes
int sleep = 200;
//每秒5次 即5*10K bytes每秒 int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
//Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}

}
}

B. C#.NET中如何解決HttpWebResponse下載網頁後的編碼轉換

試試
Encoding.Default吧

C. vb.net HttpWebResponse和HttpWebRequest 下載網頁源代碼 如何等待網頁載入完畢在在下

在HttpWebRequest.GetResponse運行完畢之後,就表示網頁已經載入完畢了。
如果是非同步獲取HttpWebResponse,沒擾那麼在HttpWebRequest.EndGetResponse之後也表示網頁加褲察滑載完胡臘畢了。

D. VB.NET如何實現文件的下載

給你一個遍歷所有盤符下的文件夾的例子加一個遍歷文件的就可以了。TreeNode node = new TreeNode("我的電腦"); treeView.Nodes.Add(node); //加入一個我的電腦節點 string[] drivesName = System.IO.Directory.GetLogicalDrives() //取得驅動器列表的集合 foreach(string name in drivesName) //用foreach遍歷集合 { TreeNode drivesNode = new TreeNode(name); node.Nodes.Add(drivesNode); //加到我的電腦節點下 }

E. ASP.NET MVC4大文件下載的問題

剛碰到這個問題,下面的代碼可以直接拷貝使用。
protected void Page_Load(object sender, EventArgs e)
{
DownFile1(@"D:\常用軟體\win7.iso", "win7.iso");
}

private void DownFile1(string filePath, string fileName)
{
ResponseFile(this.Request, this.Response, fileName, filePath, 1024000);
}
// 輸出硬碟文件,提供下載
// 輸入參數 _Request: Page.Request對象, _Response: Page.Response對象, _fileName: 下載文件名, _fullPath: 帶文件名下載路徑, _speed 每秒允許下載的位元組數
// 返回是否成功
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
//int sleep = 200; //每秒5次 即5*10K bytes每秒
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}

F. 通過.NET設計一個程序,根據用戶提供的URL去遠程http伺服器下載指定的文件

使用httprequest請求資源(資源通過url訪問),然後從httpresponse中讀取byte[](位元組數組),比如每次限量讀取10*1024 b,當然,不一定每次肯定能讀到這么多的數據,但是read是有返回值的,這個返回值正好是本次讀取到的位元組數,接下來,將這個讀取到的位元組數組寫入XML文件,同時,你在read之前記錄下時間刻度,read之後再次獲取一下時間刻度,這樣,通過兩次時間刻度差就能得出時間間隔。瞬時下載速度則為: (時間差/本次下載位元組數=下載速度) 至於單位kb/s 或 MB/S ,你可以自己去換算。

知識點:
註:httprequest,httpresponse,TimeSpan 請參照 http://msdn.microsoft.com/library/
時間刻度TimeSpan tsstart= new TimeSpan(DateTime.Now.Ticks);
TimeSpan tsend = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = tsend.Subtract(tsstart).Duration();
花費時間毫秒數 = ts.TotalMilliseconds;

G. C# 如何實現從http站點下載文件

如果不知道鏈接就先分析html文件獲得鏈接 然後

WebClient wc = new WebClient(); //創建網路通信實例
byte[] by = new byte[32]; //接收數據的數組
FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write); //創建文件
BinaryWriter bw = new BinaryWriter(fs);
while ((by = wc.DownloadData(dz)) != null) //寫文件
{
bw.Write(by, 0, by.Length);
}
FileInfo f = new FileInfo(filepath);
f.MoveTo(filepath.Remove(filepath.LastIndexOf(".temp")) + ".swf"); //更名
bw.Close();
fs.Close(); //關閉數據流
ric.AppendText(filepath + "下載完畢");

H. C #里的request如何獲取資料庫中表中的記錄

首先需要說明,在C#中REQUST有兩種.
1. 位於System.Web.HttpRequest是封裝瀏覽器對伺服器的請求的,主要用在ASP.NET中,其中包括瀏覽器請求的網址,查詢字元串數據或表單數據等等.
所以一般將System.Web.HttpReques中的Request通常都簡稱為request,即:"請求",有"請求"就有"響應(response)".

在實際開發中,最常見的使用方法就是在ASP.NET中利用request對像用於獲取FORM中各種控種的值,或者用於接收URL傳參時的值.無法用來獲取資料庫或虛擬表中的記錄.
注:FORM中各種控制項的值可以是用戶輸入,或者從資料庫中取出來的數據綁定.
例如:
Request.Params["string型參數名"],Request.QueryString["string型參數名"]用於獲取URL傳參時某個參數的值.
Request.Form["控制項名稱"]用於獲取服務端控制項FORM中的各種控制項的值.

2.位於System.Net.HttpWebRequest則是用來簡化網路請求的過程,從伺服器上獲取文件/結果的,譬如你可以在代碼中用這個類冒充瀏覽器(設置一個UserAgent)來發請求,處理回應
這里的Rquest通常用於請求獲取服務端的各種文件數據流,例如在程序中點里某個按扭將伺服器上的某個地址的文件下載到本地硬碟.這個request在使用時由先創建一個對像實例.
例如:
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("下載地址,比如說某個網址") 首先創建REQUEST對像,
request.GetResponse().GetResponseStream()創建完成後就可以通過它來獲取流中的數據了,然後將獲取的數據交給System.IO.Stream的實例對像,就可以對需要下載的數據流進行處理了.
同樣,它也有一個與之相匹配的RESPONSE響應對像.這里就不再說明了...

這種問概念性的問題記著多看看書就能找到明確的答案.
以後不要再問這么沒水平的問題了.會鬧出笑話的...

至於System.Web.HttpRequest與System.Net.HttpWebRequest具體的區別,以後從書上給抄了一段內容:

HttpWebRequest 類對 WebRequest 中定義的屬性和方法提供支持,也對使用戶能夠直接與使用 HTTP 的伺服器交互的附加屬性和方法提供支持。
不要使用 HttpWebRequest 構造函數。使用 WebRequest.Create 方法初始化新的 HttpWebRequest 對象。如果統一資源標識符 (URI) 的方案是 http:// 或 https://,則 WebRequest.Create 返回 HttpWebRequest 對象。
可以使用 BeginGetResponse 和 EndGetResponse 方法對資源發出非同步請求。喚稿BeginGetRequestStream 和 EndGetRequestStream 方法提供對發送數據流的非同步訪問。
如果在訪問資源時發生皮鎮錯誤,則 HttpWebRequest 類將引發 WebException。WebException.Status 屬性包含指示錯誤源的 WebExceptionStatus 值。
HttpWebRequest 將發送到 Internet 資源的公共 HTTP 標頭值公開為屬性,由方法或系統設置;下表包含完整列表。可以將 Headers 屬性中的其他標頭設置為名稱/值對。注意,伺服器和緩存在請求期間可能會更改或添加標頭。
下表列出了由屬性或方法設置或由系統設置的 HTTP 標頭。
System.Web.HttpRequest是封裝瀏覽器對伺服器的請求的,主要用在ASP.NET中,其中包括瀏覽器請求的網址,查詢字元串數據或表單數據等等
而System.Net.HttpWebRequest則是用來簡化網路請求的過程,從伺服器上獲取文件/結果的,譬如你可以在代碼中用這個和握孝類冒充瀏覽器(設置一個UserAgent)來發請求,處理回應
第一:他們不是父子關系。
第二:Syste.Net.HttpWebRequest類是System.Net.WebRequest抽象類的一個子類,它是.NET Framework的用於訪問Internet數據的請求/響應模型的抽象基類。使用該請求/響應模型的應用程序可以用協議不可知的方式從Internet請求數據。在這種方式下,應用程序處理 WebRequest類的實例,而協議特定的子類則執行請求的具體細節。
System.Net.HttpWebRequest類和System.Net.FileWebRequest都繼承了WebRequest
1、FileWebRequest類為使用file:// 方案來請求本地文件的URI實現WebRequest抽象基類。
2、HttpWebRequest類對WebRequest中定義的屬性和方法提供支持,也對使用戶能夠直接與使用HTTP的伺服器交互的附加屬性和方法提供支持。
第三:System.Web.HttpRequest類使ASP.NET能夠讀取客戶端在Web 請求期間發送的 HTTP值,HttpRequest類的方法和屬性通過HttpApplication、HttpContext、Page 和 UserControl類的Request屬性公開。
所以使用System.Web.HttpRequest類的時候其實都是利用HttpApplication、HttpContext、Page和UserControl類的Request屬性。而使用System.Net.HttpWebRequest類時是為了獲得一個Uri資源。自己創建。
System.Web 命名空間提供使得可以進行瀏覽器與伺服器通信的類和介面。此命名空間包括 HttpRequest 類(用於提供有關當前 HTTP 請求的廣泛信息)、HttpResponse 類(用於管理對客戶端的 HTTP 輸出)以及 HttpServerUtility 類(用於提供對伺服器端實用工具與進程的訪問)。System.Web 還包括用於 Cookie 操作、文件傳輸、異常信息和輸出緩存控制的類。
System.Net 命名空間為當前網路上使用的多種協議提供了簡單的編程介面。WebRequest 和 WebResponse 類形成了所謂的可插接式協議的基礎,可插接式協議是網路服務的一種實現,它使您能夠開發出使用 Internet 資源的應用程序,而不必考慮各種不同協議的具體細節。

I. asp.net 怎樣下載遠程圖片

#region 下載圖片並上傳至圖片伺服器
public string SaveUrlPics( string strHTML, string path)
{
string picserver = new CommonBLL().GetItemValue("PICSERVER");//獲取圖片伺服器地址
string[] imgurlAry = GetImgTag(strHTML);//獲取文章中的圖片地址
try
{
WebClient wc = new WebClient();
for (int i = 0; i < imgurlAry.Length; i++)
{
//暫時處理避免多肆薯次進行添加處理 不處理本機的情況
if(imgurlAry[i].IndexOf(picserver)<0)
{
string preStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
preStr = preStr + imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("."));//獲取圖片的屬性 生成圖片名稱
/好坦/下載的圖片存儲在TEMP文件夾中
wc.DownloadFile(imgurlAry[i], HttpContext.Current.Server.MapPath(path) + "/" + preStr);
//把圖片上傳友雹桐至圖片伺服器
preStr = picserver + "/" + upImg(preStr, dropArtType.SelectedValue);
strHTML = strHTML.Replace(imgurlAry[i], preStr);
}
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
return strHTML;
}

#endregion

J. asp.net中如何寫下載代碼

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.Text;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DownloadClass dd = new DownloadClass();
dd.StrUrl = "http://127.0.0.1/UI.rar";
dd.StrFileName="C:\\1.rar";
dd.DownloadFile();
Response.Write(dd.strError);
}
//測試用線程1斷點續傳下載網路上的文件到本地電腦
public class DownloadClass
{
public string StrUrl;//文件下載網址
public string StrFileName;//下載文件保存地址
public string strError;//返回結果
public long lStartPos = 0; //返回上次下載位元組
public long lCurrentPos = 0;//返回當前下載位元組
public long lDownloadFile;//返回當前下載文件長度

public void DownloadFile()
{
System.IO.FileStream fs;
if (System.IO.File.Exists(StrFileName))
{
fs = System.IO.File.OpenWrite(StrFileName);
lStartPos = fs.Length;
fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
//移動文件流中的當前指針
}
else
{
fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
lStartPos = 0;
}

//打開網路連接
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
long length = request.GetResponse().ContentLength;
lDownloadFile = length;
if (lStartPos > 0)
request.AddRange((int)lStartPos); //設置Range值

//向伺服器請求,獲得伺服器回應數據流
System.IO.Stream ns = request.GetResponse().GetResponseStream();

byte[] nbytes = new byte[512];
int nReadSize = 0;
nReadSize = ns.Read(nbytes, 0, 512);
while (nReadSize > 0)
{
fs.Write(nbytes, 0, nReadSize);
nReadSize = ns.Read(nbytes, 0, 512);
lCurrentPos = fs.Length;
}

fs.Close();
ns.Close();
strError = "下載完成";

}
catch (Exception ex)
{
fs.Close();
strError = "下載過程中出現錯誤:" + ex.ToString();
}

}
}
}

閱讀全文

與nethttprequest下載文件相關的資料

熱點內容
蘋果6簡訊發不了 瀏覽:524
微信的mp3時長獲取java 瀏覽:693
編程語言和程序什麼關系 瀏覽:441
windows7操作系統文件名 瀏覽:566
a鏈接下載文件 瀏覽:970
php文件運行找不到 瀏覽:103
linux查看文件及子目錄大小 瀏覽:86
初級會計學書有pdf文件嗎 瀏覽:374
淘寶大數據推薦怎麼改 瀏覽:471
怎麼恢復圖書館電腦的文件 瀏覽:7
app地址是什麼 瀏覽:357
vivoxplay6桌面文件包 瀏覽:851
手機沃郵箱下載的文件在哪裡 瀏覽:112
dnf總是閃退win10系統的 瀏覽:670
java用什麼做界面 瀏覽:281
小學數學app哪個好 瀏覽:524
用哪個公式預測數據 瀏覽:237
qq密碼查 瀏覽:983
在電腦上如何保存文件怎麼打開 瀏覽:685
淘寶虛擬店鋪裝修教程 瀏覽:458

友情鏈接