using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using Tsingda.NewLearningBar.Web.ashx;
namespace Tsingda.NewLearningBar.Activity.ashx
{
/// <summary>
/// HaoBanUploadFiles 的摘要说明
/// </summary>
public class HaoBanUploadFiles : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpPostedFile file = null;
try
{
file = context.Request.Files[0];//得到文件根据索引号
}
catch (Exception mye)
{
context.Response.Write("0|" + mye.Message.ToString());
return;
}
if (file != null)
{
Tsingda.NewLearningBar.Activity.Helper.UploadFile uf = new Tsingda.NewLearningBar.Activity.Helper.UploadFile();
UploadFileExt ufe = GetFilePath();
//上传的类别,如上传用户头像type=upload_avatar
string strType = HttpContext.Current.Request.QueryString["type"];
string[] arr = strType.Split('|');
if (arr[0] == "upload_avatar" && file.ContentLength > 3145728)
{
context.Response.Write("0|图片大小超过3M");//答疑图片必须小于3m
return;
}
if (arr[0] == "upload_avatar" && file.ContentLength <= 0)
{
context.Response.Write("0|上传图片应大于0M");//答疑图片必须大于0m
return;
}
int intWidth = 0, intHeight = 0;
if (arr.Length >= 3)
{
if (arr[1] != "" && arr[2] != "")
{
intWidth = Convert.ToInt32(arr[1]);
intHeight = Convert.ToInt32(arr[2]);
}
}
//-----------ftp上传图片------
//上传文件的指定路径+年月
string strPicturePath = string.Format("{0}{1}/", ufe.Path, DateTime.Now.ToString("yyyyMM"));
//文件的命名规则
string strFileName = DateTime.Now.ToFileTime().ToString() + "" + new Random().Next(1000, 9999).ToString();
string strPath = "";//上传成功后返回的相对路径
bool videoImg = false;
if (arr[0] == "upload_courseware")
{
videoImg = true;
}
if (uf.UploadFTP(file, ufe.Ext, ufe.Size, intWidth, intHeight, strPicturePath, strFileName, ref strPath, videoImg))
{
string[] arrPath = strPath.Split('|');
if (videoImg)
{
context.Response.Write(string.Format("1|{0}|{1}", VCommons.WebConfig.GetWebConfig("website_resource", "") + arrPath[0], VCommons.WebConfig.GetWebConfig("website_resource", "") + arrPath[1]));//域名+相对路径
}
else
{
context.Response.Write(string.Format("1|{0}", VCommons.WebConfig.GetWebConfig("website_resource", "") + arrPath[0]));//域名+相对路径
}
}
else
{
context.Response.Write("0|" + strPath);
}
}
else
{
context.Response.Write("0|error");
}
}
/// <summary>
/// 获取上传文件的扩展信息
/// </summary>
/// <returns></returns>
private UploadFileExt GetFilePath()
{
//上传文件的类型 如上传图像采用 type= upload_avatar
string type = HttpContext.Current.Request.QueryString["type"];
string[] arr = type.Split('|');
UploadFileExt data = new UploadFileExt();
if (!string.IsNullOrWhiteSpace(arr[0]))
{
string strPath = VCommons.WebConfig.GetWebConfig(arr[0] + "_path", string.Empty);
string strExt = VCommons.WebConfig.GetWebConfig(arr[0] + "_ext", string.Empty);
int intSize = Convert.ToInt32(VCommons.WebConfig.GetWebConfig(arr[0] + "_size", "0"));
if (!string.IsNullOrWhiteSpace(strPath) && !string.IsNullOrWhiteSpace(strExt) && intSize > 0)
{
data.Path = strPath;
data.Ext = strExt;
data.Size = intSize;
}
}
return data;
}
/// <summary>
/// 视频截图方法
/// </summary>
/// <param name="file">视频文件(绝对路径)</param>
/// <returns>图片绝对路径</returns>
private string CreateVideoImage(string file)
{
string p = HttpRuntime.AppDomainAppPath;
string videoFile = file;
string ffmpegfile = p + @"Images\ffmpeg.exe";
DateTime dt = DateTime.Now;
string ourFilePath = p + @"Images\ffmpegImage\" + dt.Year + "\\" + dt.Month + "\\" + dt.Day + "\\" + dt.Hour + "\\";
if (!Directory.Exists(ourFilePath))
{
Directory.CreateDirectory(ourFilePath);
}
ourFilePath += dt.Minute + "_" + dt.Millisecond + "img";
ProcessStartInfo psi = new ProcessStartInfo(ffmpegfile);
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.Arguments = " -i " + videoFile + " -r 1 -ss 00:00:10 -t 00:00:5 -s 688x389 " + ourFilePath + "%05d.png";
Process.Start(psi);
return ourFilePath + "00001.png";
}
public bool IsReusable
{
get
{
return false;
}
}
}
//默认的基本信息
class UploadFileExt
{
private string _path = "/Images/", _ext = ".jpg;.gif;.jpeg;.png";
private int _size = 3145728;
public string Path { get { return _path; } set { _path = value; } }
public string Ext { get { return _ext; } set { _ext = value; } }
public int Size { get { return _size; } set { _size = value; } }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
using Tsingda.NewLearningBar.Activity.Helper;
using VCommons;
using Tsingda.NewLearningBar.Commons;
using Tsingda.NewLearningBar.Commons.FileUpload;
namespace Tsingda.NewLearningBar.Activity.Helper
{
/// <summary>
/// 文件上传类
/// </summary>
/// <remarks>
/// Created By :王彦忠
/// Created Date:2011-9-13
/// Modify By:
/// Modify Date:
/// Modify Reason:
/// </remarks>
public class UploadFile
{
/// <summary>
/// 存放路径
/// </summary>
public string strSavePath { get; set; }
/// <summary>
/// 文件类型
/// </summary>
public string strFileExt { get; set; }
/// <summary>
/// 文件大小
/// </summary>
public int iFileLength { set; get; }
public HttpPostedFile fileUpload { set; get; }
FtpUpload ft;
public UploadFile()
{
ft = new FtpUpload();
}
public UploadFile(string ftpServerIP, string ftpUserID, string ftpPassword, string ftpPort)
{
ft = new FtpUpload(ftpServerIP, ftpUserID, ftpPassword, ftpPort);
}
#region 文件上传
/// <summary>
/// 文件上传
/// </summary>
/// <remarks>
/// Created By :王彦忠
/// Created Date:2011-9-14
/// Modify By:
/// Modify Date:
/// Modify Reason:
/// </remarks>
/// <param name="file">文件</param>
/// <param name="strPathAndName">文件存放路径和保存后的文件名</param>
/// <param name="bUploadType">是否启用断点续传</param>
/// <param name="strFileType">允许上传的文件类型 必须用分号分隔 例如.jpg;.gif</param>
/// <param name="iFileLength">允许上传的最大文件 单位:字节</param>
/// <param name="strInfo">返回的提示信息</param>
/// <returns>True:上传成功 Flase:上传失败</returns>
public bool Upload(HttpPostedFileBase file, string strPathAndName, bool bUploadType, string strFileType, int iFileLength, ref string strInfo)
{
bool bFlag = true; //返回类型
this.strFileExt = strFileType;
string strExt = file.FileName.Substring(file.FileName.LastIndexOf('.')); //文件扩展名
//检测文件类型
if (!CheckFileType(strExt))
{
bFlag = false;
strInfo = "上传文件类型错误!建议上传文件类型为" + strFileType;
return bFlag;
}
//检测文件大小
if (file.ContentLength > iFileLength)
{
bFlag = false;
strInfo = "上传文件大小已经超出规定大小!建议上传文件大小为" + iFileLength / 1024 / 1024 + "M";
return bFlag;
}
//检测存放目录
string strFileName = string.Empty;
string strFolder = string.Empty;
CreateFolderAndGetFileName(strPathAndName, strExt, ref strFolder, ref strFileName);
//开始存放文件
try
{
if (!bUploadType)
{
file.SaveAs(strFolder.Trim('\\') + @"\" + strFileName);
}
else
{
var provider = (IServiceProvider)HttpContext.Current;
var workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
var encoding = HttpContext.Current.Request.ContentEncoding;
var processor = new UploadProcessor(workerRequest);
processor.StreamToDisk(HttpContext.Current, encoding, strFolder);
}
strInfo = strPathAndName;
}
catch (Exception ex)
{
bFlag = false;
strInfo = ex.Message;
}
return bFlag;
}
public bool UploadFTP(HttpPostedFileBase file, string strFileType, int iFileLength, int Width, int Height, string Path, ref string strInfo, bool VideoImg)
{
return UploadFTP(file, strFileType, iFileLength, Width, Height, Path, string.Empty, ref strInfo, VideoImg);
}
public bool UploadFTP(HttpPostedFileBase file, string strFileType, int iFileLength, int Width, int Height, string Path, string fileName, ref string strInfo, bool VideoImg)
{
if (strFileType.ToLower().Split(';').Contains(System.IO.Path.GetExtension(file.FileName).ToLower()) == false)
{
strInfo = "请按照指定的文件类型上传!";
return false;
}
if (file.ContentLength > iFileLength)
{
strInfo = "请按照指定的大小上传!";
return false;
}
try
{
string strName = "";
if (!string.IsNullOrEmpty(fileName))
{
strName = string.Format("{0}{1}", fileName, System.IO.Path.GetExtension(file.FileName));
}
else
{
strName = string.Format("{0}{1}", DateTime.Now.ToFileTime().ToString() + "" + new Random().Next(1000, 9999), System.IO.Path.GetExtension(file.FileName));
}
if (!Directory.Exists(HttpContext.Current.Server.MapPath("~") + "Temp/"))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~") + "Temp/");
}
string strCurPath = "Temp/" + strName,
strLocalFile = HttpContext.Current.Server.MapPath("~") + strCurPath;
//-----普通上传
if ((Width == 0 || Height == 0) && !this.Upload(file, strCurPath, false, strFileType, iFileLength, ref strInfo))
{
return false;
}
//----压缩图片----
if (Width > 0 && Height > 0)
{
bool flag = CreateThumbnail(file, Width, Height, true, strLocalFile);
if (!flag)
{
strInfo = "压缩图片失败";
return false;
}
}
bool bFlag = ft.Upload(strLocalFile, strName, Path);//ftp上传
string imgPath = "";
string imgName = "";
if (VideoImg && bFlag)//视频截图
{
string vImgStr = CreateVideoImage(strLocalFile);//返回绝对路径
DateTime dt = DateTime.Now;
imgPath = Path + "VideoImg/" + dt.Year + "/" + dt.Month + "/" + dt.Day + "/" + dt.Hour + "/";//截图上传ftp路径
string tempvImgStr = vImgStr.Substring(0, vImgStr.Length - 5);
imgName = System.IO.Path.GetFileName(vImgStr);//图片的名称
string tempImgName = imgName.Substring(0, imgName.Length - 5);
//8张图片上传
for (int i = 1; i < 8; i++)
{
imgName = tempImgName + (i + ".png");
vImgStr = tempvImgStr + (i + ".png");
bFlag = ft.Upload(vImgStr, imgName, imgPath);//上传视频截图
}
//清除本地多余的图片,有的视频截取的图片多,有的视频截取的图片少
string tempImgDir = HttpContext.Current.Server.MapPath("/Images/ffmpegImage");
string[] strArr = Directory.GetFiles(tempImgDir);
foreach (var strpath in strArr)
{
File.Delete(strpath);
}
}
if (bFlag)
{
strInfo = string.Format("{0}{1}", Path, strName) + "|" + string.Format("{0}{1}", imgPath, imgName);
}
FileInfo fileInfo = new FileInfo(strLocalFile);
fileInfo.Delete();
return bFlag;
}
catch
{
strInfo = "上传异常";
}
return false;
}
/// <summary>
/// 上传文件到ftp上
/// </summary>
/// <param name="file"></param>
/// <param name="strFileType">用;号割开。例如:.jpg;.png;.gif</param>
/// <param name="iFileLength"></param>
/// <param name="Width"></param>
/// <param name="Height"></param>
/// <param name="Path"></param>
/// <param name="strInfo"></param>
/// <returns></returns>
public bool UploadFTP(HttpPostedFile file, string strFileType, int iFileLength, int Width, int Height, string Path, string fileName, ref string strInfo, bool VideoImg)
{
HttpPostedFileBase hpfb = new HttpPostedFileWrapper(file) as HttpPostedFileBase;
return UploadFTP(hpfb, strFileType, iFileLength, Width, Height, Path, fileName, ref strInfo, VideoImg);
}
public bool UploadFTP(HttpPostedFile file, string strFileType, int iFileLength, int Width, int Height, string Path, ref string strInfo, bool VideoImg)
{
return UploadFTP(file, strFileType, iFileLength, Width, Height, Path, string.Empty, ref strInfo, VideoImg);
}
/// <summary>
/// 视频截图方法
/// </summary>
/// <param name="file">视频文件(绝对路径)</param>
/// <returns>图片绝对路径</returns>
private string CreateVideoImage(string file)
{
string p = HttpRuntime.AppDomainAppPath;
string videoFile = file;
string ffmpegfile = p + @"Images\ffmpeg.exe";
DateTime dt = DateTime.Now;
string ourFilePath = p + @"Images\ffmpegImage\";
if (!Directory.Exists(ourFilePath))
{
Directory.CreateDirectory(ourFilePath);
}
ourFilePath += dt.Minute + "_" + dt.Millisecond + "img";
ProcessStartInfo psi = new ProcessStartInfo(ffmpegfile);
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.Arguments = " -i " + videoFile + " -r 1 -ss 00:00:08 -t 00:00:12 -s 688x389 " + ourFilePath + "%05d.png";
System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
process.WaitForExit();
return ourFilePath + "00001.png";
}
#endregion
#region 检测文件类型是否正确
/// <summary>
/// 检测文件类型是否正确
/// </summary>
/// <remarks>
/// Created By :王彦忠
/// Created Date:2011-9-13
/// Modify By:
/// Modify Date:
/// Modify Reason:
/// </remarks>
/// <param name="strExt">文件类型</param>
/// <returns>True:满足条件 False:不符合条件</returns>
public bool CheckFileType(string strExt)
{
foreach (string str in strFileExt.Trim(';').Split(';'))
{
if (str.Equals(strExt, StringComparison.CurrentCultureIgnoreCase))
{
return true;
}
}
return false;
}
#endregion
#region 创建文件夹和获取保存文件的名字
/// <summary>
/// 创建文件夹和获取保存文件的名字
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="strPath">文件路径</param>
/// <param name="strExt">文件扩展名</param>
/// <param name="strFolder">文件夹路径</param>
/// <param name="strFileName">文件名字</param>
/// <returns>返回文件名</returns>
public void CreateFolderAndGetFileName(string strPath, string strExt, ref string strFolder, ref string strFileName)
{
strPath = strPath.Trim('/');
if (strPath.IndexOf('.') > 0)
{
strFileName = strPath.Substring(strPath.LastIndexOf('/') + 1);
strFolder = strPath.Substring(0, strPath.LastIndexOf('/'));
}
else
{
strFileName = Guid.NewGuid() + strExt;
strFolder = "/" + strPath + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
}
strPath = "/" + strFolder;
strFolder = HttpContext.Current.Server.MapPath(strPath);
if (!Directory.Exists(strFolder))
{
Directory.CreateDirectory(strFolder);
}
}
#endregion
Point point = new Point(0, 0); //图像从那个坐标点进行截取
double wRate = 1, hRate = 1, setRate = 1;
int newWidth = 0, newHeight = 0;
/// <summary>
/// 图像的缩放
/// </summary>
/// <param name="file">缩放文件</param>
/// <param name="width">宽</param>
/// <param name="height">高</param>
/// <param name="isEqualScale">是否等比例缩放</param>
/// <param name="name">缩放后存放的地址</param>
/// <returns></returns>
public bool CreateThumbnail(HttpPostedFileBase file, double width, double height, bool isEqualScale, string name)
{
try
{
System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream);
if (isEqualScale)
{
if (image.Height > height)
{
hRate = height / image.Height;
}
if (image.Width > width)
{
wRate = width / image.Width;
}
if (wRate != 1 || hRate != 1)
{
if (wRate > hRate)
{
setRate = hRate;
}
else
{
setRate = wRate;
}
}
newWidth = (int)(image.Width * setRate);
newHeight = (int)(image.Height * setRate);
if (height > newHeight)
{
point.Y = Convert.ToInt32(height / 2 - newHeight / 2);
}
if (width > newWidth)
{
point.X = Convert.ToInt32(width / 2 - newWidth / 2);
}
}
Bitmap bit = new Bitmap((int)(width), (int)(height));
Rectangle r = new Rectangle(point.X, point.Y, (int)(image.Width * setRate), (int)(image.Height * setRate));
Graphics g = Graphics.FromImage(bit);
g.Clear(Color.White);
g.DrawImage(image, r);
MemoryStream ms = new MemoryStream();
bit.Save(ms, ImageFormat.Jpeg);
byte[] bytes = ms.ToArray();
string fileName = name;
using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
stream.Write(bytes, 0, bytes.Length);
}
bit.Dispose();
ms.Dispose();
image.Dispose();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 上传图片
/// </summary>
/// <param name="stream"></param>
/// <param name="fileName"></param>
/// <param name="message"></param>
/// <returns></returns>
public static string UploadImg(Stream stream, string fileName, ref string message)
{
string imgPath = FileUploaderFactory.GetFileUploader().SmallFileUpload(new ImgUploadParameter(stream, fileName), ref message);
return imgPath;
}
}
}