WebClient HttpWebRequest 下载文件到本地
处理方式:
第一种: 我们需要获取文件,但是我们不需要保存源文件的名称
public void DownFile(string uRLAddress, string localPath, string filename)
{
WebClient client = new WebClient();
Stream str = client.OpenRead(uRLAddress);
StreamReader reader = new StreamReader(str);
byte[] mbyte = new byte[1000000];
int allmybyte = (int)mbyte.Length;
int startmbyte = 0;
while (allmybyte > 0)
{
int m = str.Read(mbyte, startmbyte, allmybyte);
if (m == 0)
{
break;
}
startmbyte += m;
allmybyte -= m;
}
reader.Dispose();
str.Dispose();
//string paths = localPath + System.IO.Path.GetFileName(uRLAddress);
string path = localPath + filename;
FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(mbyte, 0, startmbyte);
fstr.Flush();
fstr.Close();
}
第二种:我们需要获取文件,但是希望可以获取到文件的原名称以及其他的信息
/// <summary>
/// 文件下载
/// </summary>
/// <param name="url">所下载的路径</param>
/// <param name="path">本地保存的路径</param>
/// <param name="overwrite">当本地路径存在同名文件时是否覆盖</param>
/// <param name="callback">实时状态回掉函数</param>
/// Action<文件名,文件的二进制, 文件大小, 当前已上传大小>
public static void HttpDownloadFile(string url, string path, bool overwrite, Action<string,string, byte[], long, long> callback = null)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//获取文件名
string fileName = response.Headers["Content-Disposition"];//attachment;filename=FileName.txt
string contentType = response.Headers["Content-Type"];//attachment;
if (string.IsNullOrEmpty(fileName))
fileName = response.ResponseUri.Segments[response.ResponseUri.Segments.Length - 1];
else
fileName = fileName.Remove(0, fileName.IndexOf("filename=") + 9);
//直到request.GetResponse()程序才开始向目标网页发送Post请求
using (Stream responseStream = response.GetResponseStream())
{
long totalLength = response.ContentLength;
///文件byte形式
byte[] b = ImageHelper.ImageToByte1(url);
//创建本地文件写入流
if (System.IO.File.Exists(Path.Combine(path, fileName))) {
fileName = DateTime.Now.Ticks + fileName;
}
using (Stream stream = new FileStream(Path.Combine(path, fileName), overwrite ? FileMode.Create : FileMode.CreateNew))
{
byte[] bArr = new byte[1024];
int size;
while ((size = responseStream.Read(bArr, 0, bArr.Length)) > 0)
{
stream.Write(bArr, 0, size);
callback.Invoke(fileName,contentType, b, totalLength, stream.Length);
}
}
}
}
但是这并不是绝对的,第一种方法当地址是 :
http://128.1.3.67:8083/api/wap/v2/fs/image/d4cbc75704ece271a5e0f1765346587f.jpg 时我们一样可以获取到名称
使用:System.IO.Path.GetFileName(uRLAddress)
浙公网安备 33010602011771号