using Seaskyer.FSO;
using Seaskyer.Strings;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
namespace Seaskyer.WebApp.Utility
{
/// <summary>
/// WebUtility : 基于System.Web的拓展类。
///
/// </summary>
public class WebUtility
{
/// <summary>
/// 检测指定的 Uri 是否有效
///
/// </summary>
/// <param name="url">指定的Url地址</param>
/// <returns>
/// bool
/// </returns>
public static bool ValidateUrl(string url)
{
Uri requestUri = new Uri(url);
try
{
return ((HttpWebResponse) WebRequest.Create(requestUri).GetResponse()).StatusCode == HttpStatusCode.OK;
}
catch
{
return false;
}
}
/// <summary>
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
///
/// </summary>
/// <param name="_fileName">下载文件名</param><param name="_fullPath">带文件名下载路径</param><param name="_speed">每秒允许下载的字节数</param>
/// <returns>
/// 返回是否成功
/// </returns>
public static bool DownloadFile(string _fullPath, string _fileName, long _speed)
{
HttpRequest request = HttpContext.Current.Request;
HttpResponse response = HttpContext.Current.Response;
try
{
FileStream fileStream = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader binaryReader = new BinaryReader((Stream) fileStream);
try
{
response.AddHeader("Accept-Ranges", "bytes");
response.Buffer = false;
long length = fileStream.Length;
long offset = 0L;
int count = 10240;
int millisecondsTimeout = (int) Math.Floor((double) ((long) (1000 * count) / _speed)) + 1;
if (request.Headers["Range"] != null)
{
response.StatusCode = 206;
offset = Convert.ToInt64(request.Headers["Range"].Split(new char[2]
{
'=',
'-'
})[1]);
}
response.AddHeader("Content-Length", (length - offset).ToString());
if (offset != 0L)
response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", (object) offset, (object) (length - 1L), (object) length));
response.AddHeader("Connection", "Keep-Alive");
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, Encoding.UTF8));
binaryReader.BaseStream.Seek(offset, SeekOrigin.Begin);
int num = (int) Math.Floor((double) ((length - offset) / (long) count)) + 1;
for (int index = 0; index < num; ++index)
{
if (response.IsClientConnected)
{
response.BinaryWrite(binaryReader.ReadBytes(count));
Thread.Sleep(millisecondsTimeout);
}
else
index = num;
}
}
catch
{
return false;
}
finally
{
binaryReader.Close();
fileStream.Close();
}
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 下载服务器上的文件(适用于非WEB路径下,且是大文件,该方法在IE中不会显示下载进度)
///
/// </summary>
/// <param name="path">下载文件的绝对路径</param><param name="saveName">保存的文件名,包括后缀符</param>
public static void Download(string path, string saveName)
{
HttpResponse response = HttpContext.Current.Response;
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(saveName, Encoding.UTF8));
response.TransmitFile(path);
response.End();
}
/// <summary>
/// 下载服务器上的文件(适用于非WEB路径下,且是大文件,该方法在IE中会显示下载进度)
///
/// </summary>
/// <param name="path">下载文件的绝对路径</param><param name="saveName">保存的文件名,包括后缀符</param>
public static void DownloadFile(string path, string saveName)
{
Stream stream = (Stream) null;
byte[] buffer = new byte[10240];
string path1 = path;
Path.GetFileName(path1);
try
{
stream = (Stream) new FileStream(path1, FileMode.Open, FileAccess.Read, FileShare.Read);
HttpContext.Current.Response.Clear();
long num1 = stream.Length;
long num2 = 0L;
if (HttpContext.Current.Request.Headers["Range"] != null)
{
HttpContext.Current.Response.StatusCode = 206;
num2 = long.Parse(HttpContext.Current.Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
}
if (num2 != 0L)
HttpContext.Current.Response.AddHeader("Content-Range", "bytes " + num2.ToString() + "-" + (num1 - 1L).ToString() + "/" + num1.ToString());
HttpContext.Current.Response.AddHeader("Content-Length", (num1 - num2).ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(saveName, Encoding.UTF8));
stream.Position = num2;
num1 -= num2;
while (num1 > 0L)
{
if (HttpContext.Current.Response.IsClientConnected)
{
int count = stream.Read(buffer, 0, 10240);
HttpContext.Current.Response.OutputStream.Write(buffer, 0, count);
HttpContext.Current.Response.Flush();
buffer = new byte[10240];
num1 -= (long) count;
}
else
num1 = -1L;
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error : " + ex.Message);
}
finally
{
if (stream != null)
stream.Close();
HttpContext.Current.Response.End();
}
}
/// <summary>
/// 从指定的URL下载页面内容(使用WebRequest)
///
/// </summary>
/// <param name="url">指定URL</param>
/// <returns/>
public static string LoadURLString(string url)
{
Stream responseStream = WebRequest.Create(url).GetResponse().GetResponseStream();
string str1 = "";
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312"));
char[] chArray = new char[256];
int length = streamReader.Read(chArray, 0, 256);
int num = 0;
for (; length > 0; length = streamReader.Read(chArray, 0, 256))
{
num += Encoding.UTF8.GetByteCount(chArray, 0, 256);
string str2 = new string(chArray, 0, length);
str1 = str1 + str2;
}
return str1;
}
/// <summary>
/// 从指定的URL下载页面内容(使用WebClient)
///
/// </summary>
/// <param name="url">指定URL</param>
/// <returns/>
public static string LoadPageContent(string url)
{
return Encoding.GetEncoding("gb2312").GetString(new WebClient()
{
Credentials = CredentialCache.DefaultCredentials
}.DownloadData(url));
}
/// <summary>
/// 远程提取文件保存至服务器上(使用WebRequest)
///
/// </summary>
/// <param name="url">一个URI上的文件</param><param name="saveurl">文件保存在服务器上的全路径</param>
public static void RemoteGetFile(string url, string saveurl)
{
HttpWebResponse httpWebResponse = (HttpWebResponse) WebRequest.Create(url).GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
int num = (int) httpWebResponse.ContentLength;
int bufferSize = 102400;
byte[] buffer = new byte[bufferSize];
FObject.WriteFile(saveurl, "temp");
FileStream fileStream = System.IO.File.Create(saveurl, bufferSize);
int count;
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
fileStream.Write(buffer, 0, count);
}
while (count > 0);
fileStream.Flush();
fileStream.Close();
responseStream.Flush();
responseStream.Close();
}
/// <summary>
/// 远程提取一个文件保存至服务器上(使用WebClient)
///
/// </summary>
/// <param name="url">一个URI上的文件</param><param name="saveurl">保存文件</param>
public static void WebClientGetFile(string url, string saveurl)
{
WebClient webClient = new WebClient();
try
{
FObject.WriteFile(saveurl, "temp");
webClient.DownloadFile(url, saveurl);
}
catch
{
}
webClient.Dispose();
}
/// <summary>
/// 远程提取一组文件保存至服务器上(使用WebClient)
///
/// </summary>
/// <param name="urls">一组URI上的文件</param><param name="saveurls">保存文件</param>
public static void WebClientGetFile(string[] urls, string[] saveurls)
{
WebClient webClient = new WebClient();
for (int index = 0; index < urls.Length; ++index)
{
try
{
webClient.DownloadFile(urls[index], saveurls[index]);
}
catch
{
}
}
webClient.Dispose();
}
/// <summary>
/// 上传文件
///
/// </summary>
/// <param name="upfile">获取客户段上传的文件</param><param name="limitType">允许上传的文件类型,null值为无限制</param><param name="limitSize">上传文件的大小限制(0为无限制)</param><param name="autoName">是否自动命名</param><param name="savepath">上传文件的保存路径</param>
/// <returns>
/// string[]
/// </returns>
public static string[] UploadFile(HttpPostedFile upfile, string limitType, int limitSize, bool autoName, string savepath)
{
string[] strArray1 = new string[5];
string[] strArray2 = (string[]) null;
if (!object.Equals((object) limitType, (object) null) || object.Equals((object) limitType, (object) ""))
strArray2 = Function.SplitArray(limitType, ',');
int contentLength = upfile.ContentLength;
string fileName1 = upfile.FileName;
string fileName2 = Path.GetFileName(fileName1);
if (fileName2 == null || fileName2 == "")
{
strArray1[0] = "无文件";
strArray1[1] = "";
strArray1[2] = "";
strArray1[3] = "";
strArray1[4] = "<font color=red>失败</font>";
return strArray1;
}
else
{
string contentType = upfile.ContentType;
string[] strArray3 = Function.SplitArray(fileName2, '.');
string strA = strArray3[strArray3.Length - 1];
int length = fileName2.Length - strA.Length - 1;
string str1 = (!autoName ? fileName2.Substring(0, length) : "_" + Function.Str.MakeName()) + "." + strA;
strArray1[0] = fileName1;
strArray1[1] = str1;
strArray1[2] = contentType;
strArray1[3] = contentLength.ToString();
bool flag = false;
if (limitSize <= contentLength && limitSize != 0)
{
strArray1[4] = "<font color=red>失败</font>,上传文件过大";
flag = false;
}
else if (strArray2 != null)
{
for (int index = 0; index <= strArray2.Length - 1; ++index)
{
if (string.Compare(strA, strArray2[index].ToString(), true) == 0)
{
flag = true;
break;
}
else
{
strArray1[4] = "<font color=red>失败</font>,文件类型不允许上传";
flag = false;
}
}
}
else
flag = true;
if (flag)
{
try
{
string str2 = savepath + str1;
FObject.WriteFile(str2, "临时文件");
upfile.SaveAs(str2);
strArray1[4] = "成功";
}
catch (Exception ex)
{
strArray1[4] = "<font color=red>失败</font><!-- " + ex.Message + " -->";
}
}
return strArray1;
}
}
}
}
代码简单易懂,就不解释了
文件下载地址:点击下载