最近在公司做一个简单的运行于苹果Ipad上的电子书阅读软件,其中有一个小功能就是将服务器上的图片下载并保存到本地(需要调用的一个数据库中的表中的图片的路径是保存在不同于源码所在的服务器上的)。我承认自己的能力极为有限,见识也少,没接触过这些东西,一点没头绪,就在网上查资料,也没找着多少。因此就在自己的技术群里请教,收获了一些相关资料。总结起来,总共有以下几种方法:
一、利用了.net下命名空间System.Net的WebClient和System.IO (这种方法测试能运行)
/// <summary>
/// 下载文件
/// </summary>
/// <param name="URL"></param>
public static void downloadfile(string URL)
{
WebClient client = new WebClient();
int n = URL.LastIndexOf(\'/\');//获取URL的最后一个/
string URLAddress = URL.Substring(0, n); //取得除文件名和最后一个/后的路径
string fileName = URL.Substring(n + 1, URL.Length - n - 1); //取得文件名
string savePath = "../" + ConfigurationManager.AppSettings["BookCoverPath"];
string Dir = System.Web.HttpContext.Current.Server.MapPath(savePath); //下载文件存放路径
string Pathstr = Dir + fileName; //下载文件存放完整路径
Stream stream = client.OpenRead(URL);
StreamReader reader = new StreamReader(stream);
byte[] mbyte = new byte[100000];
int allbyte = (int)mbyte.Length;
int startbyte = 0;
while (allbyte > 0) //循环读取
{
int m = stream.Read(mbyte, startbyte, allbyte);
if (m == 0)
break;
startbyte += m;
allbyte -= m;
}
FileStream fstr = new FileStream(Pathstr, FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(mbyte, 0, startbyte); //写文件
stream.Close();
fstr.Close();
}
二、利用了HttpRequest 和HttpResponse(经测试运行时抛出不支持uri格式,uri格式是怎么回事,我也没弄明白~·~)
下载函数如下:
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;
}
在Page_Load中添加如下代码:
Page.Response.Clear(); bool success = ResponseFile(Page.Request, Page.Response, "目的文件名称", @"源文件路径", 1024000);
if (!success)
Response.Write("下载文件出错!");
Page.Response.End();
三、利用的.net下命名空间System.Net的WebClient 的DownloadFile方法(这个局限太大,只能把下载到的图片保存于bin\Debug)
用了控制台程序测试
string remoteUri = "http://218.249.32.153/Web_ApaRSDownLoad/";
string fileName = "ISBN7-5053-8089-3.bmp", myStringWebResource = null;
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myStringWebResource = remoteUri + fileName;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
Console.ReadLine();
在这几个方法中,结实了命名空间System.Net的WebClient下的一些属性方法等,有朋友做过类似的功能,欢迎分享与交流。