WebRequest myrequest = WebRequest.Create(CompanyLogoUrl);
using (HttpWebResponse response = myrequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK)
{
Stream rs = response.GetResponseStream();//rs.Length 此流不支持查找,先轉爲MemoryStream
var ms = StreamToMemoryStream(rs);
ms.Seek(0, SeekOrigin.Begin);
int buffsize = (int)ms.Length;
byte[] bytes = new byte[buffsize];
ms.Read(bytes, 0, buffsize);
string strPictureType = Path.GetExtension(CompanyLogoUrl).Substring(1);//圖片類型
var supportedTypes = new[] { "pjpeg", "jpeg", "jpg", "gif", "png" };//{ "pjpeg", "jpeg", "jpg", "gif", "bmp", "png" }
if (supportedTypes.Contains(strPictureType, StringComparer.OrdinalIgnoreCase))
{
if (buffsize != 0 && buffsize <= 512000)
{
string fileName = Path.GetFileName(CompanyLogoUrl);
string fileID = ServiceFactory.GetFileCenterService().SaveFile(fileName, bytes);//保存在數據庫方法
string path = ConfigrationHelper.FileCenterDomain + "/Home/GetFile/" + fileID;
result = path + "$" + fileName;
}
}
ms.Flush(); ms.Close();
rs.Flush(); rs.Close();
}
}數據庫
protected MemoryStream StreamToMemoryStream(Stream instream)
{
MemoryStream outstream = new MemoryStream();
int bufferLen = 512000;//圖片大小限制
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = instream.Read(buffer, 0, bufferLen)) > 0)
{
outstream.Write(buffer, 0, count);
}
return outstream;
}圖片