/// <summary>
/// 请求下载文件
/// </summary>
/// <param name="fileName">传进来的文件名</param>
/// <returns></returns>
public ActionResult GetStream(string fileName= "123.xls",string url="")
{
//获取cookie
string cookies= Getcoookie();
//本地临时文件夹
string tempFile = Path.GetTempPath();
//拼接
tempFile =Path.Combine(tempFile, fileName);
try
{
using (var client = new WebClient())
{
CookieContainer cookie = new CookieContainer();
//请求头带cookie过去
client.Headers.Add(HttpRequestHeader.Cookie, cookies);
//保存到本地文件
client.DownloadFile(url, tempFile);
//Console.WriteLine("using" + tempFile);
//给浏览器返回文件流
return File(FileToStream(tempFile, true), "application/octet-stream", fileName);
}
}
catch (Exception ex)
{
return Json("");
}
}
/// <summary>
/// 读取下载好的文件,并且删除
/// </summary>
/// <param name="fileName"></param>
/// <param name="isDelete"></param>
/// <returns></returns>
public static Stream FileToStream(string fileName, bool isDelete = false)
{
//读取文件
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
Stream stream = new MemoryStream(bytes);
//删除
if (isDelete)
{
System.IO.File.Delete(fileName);
}
//返回文件流
return stream;
}
/// <summary>
/// 获取cookie
/// </summary>
/// <returns></returns>
public static string Getcoookie()
{
string cookies = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.4399.com/action指定向");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.AllowAutoRedirect = false;
//表单传递的账号密码
string builder = "User=123&password=123456789";
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
request.ContentLength = data.Length;
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
var cookie = new CookieContainer();
request.CookieContainer = cookie;
request.CookieContainer.SetCookies(request.RequestUri, cookies);//将登录的cookie值赋予此次的请求。
HttpWebResponse respContent = (HttpWebResponse)request.GetResponse();
// string html = new StreamReader(respContent.GetResponseStream()).ReadToEnd();
//cookie拼接
if (respContent.Cookies.Count > 0)
{
for (int i = 0; i < respContent.Cookies.Count; i++)
{
cookies += respContent.Cookies[i].Name+"="+ respContent.Cookies[i].Value;
if (i != respContent.Cookies.Count - 1)
{
cookies += ";";
}
}
}
return cookies;
}