/// <summary>
/// 单个文件保存从对方服务器到自己网站
/// </summary>
/// <param name="aUrl"></param>
/// <param name="aPath"></param>
/// <returns></returns>
[HttpGet]
public string FileSave(string aUrl,string aPath) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(aUrl);
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK)
{
Stream rs = response.GetResponseStream();
//网络流转换为内存流
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 bPath = Server.MapPath(@"~/Upload/") + aPath; //winform可写物理磁盘路径d:/123.rar
string bPathS = System.IO.Path.GetDirectoryName(bPath);
if (!Directory.Exists(bPathS))
Directory.CreateDirectory(bPathS);
FileStream fs = new FileStream(bPath, FileMode.Create, FileAccess.Write);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
ms.Flush(); ms.Close();
rs.Flush(); rs.Close();
//以文件流的方式下载
}
}
return "ok";
}
/// <summary>
/// 单个文件保存从对方服务器到自己网站
/// </summary>
/// <param name="aUrl">对方服务器请求路径</param>
/// <param name="aPath">本网站存储路径</param>
/// <returns></returns>
[HttpGet]
public string FileSave(string aUrl, string aPath)
{
System.GC.Collect();
System.Net.ServicePointManager.DefaultConnectionLimit = 512;
HttpWebRequest request = null;
try
{
request = (HttpWebRequest)WebRequest.Create(aUrl);
request.Method = "GET";
request.KeepAlive = false;
request.Proxy = WebRequest.DefaultWebProxy;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength > 1000)
{
Stream rs = response.GetResponseStream();
//网络流转换为内存流
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 bPath = Server.MapPath(@"~") + aPath;
string bPathS = System.IO.Path.GetDirectoryName(bPath);
if (!Directory.Exists(bPathS))
Directory.CreateDirectory(bPathS);
FileStream fs = new FileStream(bPath, FileMode.Create, FileAccess.Write);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
ms.Flush(); ms.Close();
rs.Flush(); rs.Close();
//以文件流的方式下载
}
else
{
return "fail";
}
}
return "ok";
}
catch (Exception e)
{
return "error";
}
finally
{
if (request != null)
request.Abort();//关闭连接
}
}
private static MemoryStream StreamToMemoryStream(Stream instream)
{
MemoryStream outstream = new MemoryStream();
const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = instream.Read(buffer, 0, bufferLen)) > 0)
{
outstream.Write(buffer, 0, count);
}
return outstream;
}
03-22