處理方式:
第一種: 我們需要獲取文件,但是我們不需要保存源文件的名稱
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)
