下载文件或图片
2015-12-29 16:44
267 查看
public static void DownloadToLocal(string url, string savePath)
{
try
{
//string UploadPhysPath = ConfigurationManager.AppSettings["UploadPhysPath"];
string UploadPhysPath = BLL.CommonFileManager.UploadPhysPath;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream stream = httpWebResponse.GetResponseStream();
// 获得请求的文件大小。
int fileSize = (int)httpWebResponse.ContentLength;
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
string directory = Path.GetDirectoryName(UploadPhysPath + savePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// 建立一个写入文件的流对象。
FileStream saveFile = File.Create(UploadPhysPath + savePath, bufferSize);
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
saveFile.Write(buffer, 0, bytesRead);
}
while (bytesRead > 0);
saveFile.Flush();
saveFile.Close();
stream.Flush();
stream.Close();
}
catch (Exception e)
{
throw;
}
}
{
try
{
//string UploadPhysPath = ConfigurationManager.AppSettings["UploadPhysPath"];
string UploadPhysPath = BLL.CommonFileManager.UploadPhysPath;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream stream = httpWebResponse.GetResponseStream();
// 获得请求的文件大小。
int fileSize = (int)httpWebResponse.ContentLength;
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
string directory = Path.GetDirectoryName(UploadPhysPath + savePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// 建立一个写入文件的流对象。
FileStream saveFile = File.Create(UploadPhysPath + savePath, bufferSize);
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
saveFile.Write(buffer, 0, bytesRead);
}
while (bytesRead > 0);
saveFile.Flush();
saveFile.Close();
stream.Flush();
stream.Close();
}
catch (Exception e)
{
throw;
}
}
相关文章推荐
- 【spring】spring配置文件命名空间(如:xmlns:beans="http://www.springframework.org/schema/beans")
- linux 内核升级
- C#ProgressBar控件和 TrackBar控件
- mybatis 时间区间比较
- Mac上的抓包工具Charles
- PHPStudy+eclipse环境配置
- javascript中类型之间的转换
- socket select模型
- 阅读《Android 从入门到精通》(8)——编辑框
- Runtime之objc_msgSend函数
- jQuery.extend 函数详解
- 文章标题
- TableView性能优化——动态cell适应工具(UITableView+FDTemplateLayoutCell)
- Cannot load library: soinfo_link_image(linker.cpp:1635)
- Spring项目中使用Junit单元测试并配置数据源的问题
- 无意间把你的个人资料当圣诞礼物,送给了网络犯罪份子吗?
- ios 收起键盘
- Java反射
- IOS:UIPickerView设置三组数据联动的选择框(地区,上课时间段等类型数据的选择)
- 学习资料下载地址