/// <summary>
/// Upload 的摘要说明
/// </summary>
public class Upload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string result = AppConst.StringNull;
string _productID = context.Request.QueryString["productid"];
HttpPostedFile MyFile = context.Request.Files["Filedata"];
//int FileLen;
System.IO.Stream MyStream;
//FileLen = MyFile.ContentLength;
//byte[] input = new byte[FileLen];
// Initialize the stream.
MyStream = MyFile.InputStream;
// Read the file into the byte array.
//MyStream.Read(input, 0, FileLen);
try
{
//ProductInfo productInfo = ProductManager.GetInstance().LoadProduct(_productID);
//if (productInfo.BasicInfo == null)
//{
// //throw new BizException("该商品不存在");
//}
int picCount = 10001;
double ratio;//用来保持宽、高同比例放大或缩小
//FTP服务器用户名和密码
string ftpUserName = "liuxu";
string ftpPassword = "Ltx#2046";
//图片保存路径,作为拼接图片路径用
string originalPath = "http://www.cnblogs.com/tianxiang2046/admin/ftp://192.168.1.101/ProductOriginalImage/%22;//原图保存路径
string colorPath = "http://www.cnblogs.com/tianxiang2046/admin/ftp://192.168.1.101/ProductColorImage/%22;//色图
string smallPath = "http://www.cnblogs.com/tianxiang2046/admin/ftp://192.168.1.101/ProductSmallImage/%22;//小图
string mediumPath = "http://www.cnblogs.com/tianxiang2046/admin/ftp://192.168.1.101/ProductImage/%22;//中图
string bigPath = "http://www.cnblogs.com/tianxiang2046/admin/ftp://192.168.1.101/ProductBigImage/%22;//大图
//图片地址全名包括路径
string original1 = AppConst.StringNull;//原图保存路径
string color1 = AppConst.StringNull;//色图
string small1 = AppConst.StringNull;//小图
string medium1 = AppConst.StringNull;//中图
string big1 = AppConst.StringNull;//大图
//图片不同尺寸大小:原图、色图、小图、中图、大图
int colorsizeH = 30;
int colorsizeW = 30;
int smallsizeH = 60;
int smallsizeW = 60;
int mediumsizeH = 200;
int mediumsizeW = 200;
int bigsizeH = 1000;
int bigsizeW = 1000;
//拼接图片路径
if (picCount == 0)
{
original1 = originalPath + _productID + ".jpg";
color1 = colorPath + _productID + ".jpg";
small1 = smallPath + _productID + ".jpg";
medium1 = mediumPath + _productID + ".jpg";
big1 = bigPath + _productID + ".jpg";
}
else
{
original1 = originalPath + picCount.ToString() + "_" + _productID + ".jpg";
color1 = colorPath + picCount.ToString() + "_" + _productID + ".jpg";
small1 = smallPath + picCount.ToString() + "_" + _productID + ".jpg";
medium1 = mediumPath + picCount.ToString() + "_" + _productID + ".jpg";
big1 = bigPath + picCount.ToString() + "_" + _productID + ".jpg";
}
FTPHelper fTPHelper = new FTPHelper(originalPath, ftpUserName, ftpPassword);
//判断上传控件中有没有图片)
System.Drawing.Image original = System.Drawing.Image.FromStream(MyStream);
int originalH = original.Height;
int originalW = original.Width;
//设置大图的尺寸
if (originalW > originalH)
{
ratio = originalW / originalH;
bigsizeH = (int)(bigsizeW * ratio);
mediumsizeH = (int)(mediumsizeW * ratio);
smallsizeH = (int)(smallsizeW * ratio);
colorsizeH = (int)(colorsizeW * ratio);
}
else
{
ratio = originalH / originalW;
bigsizeW = (int)(bigsizeH * ratio);
mediumsizeW = (int)(mediumsizeH * ratio);
smallsizeW = (int)(smallsizeH * ratio);
colorsizeW = (int)(colorsizeH * ratio);
}
//保存大尺寸图片
System.Drawing.Image largeImage = new Bitmap(bigsizeW, bigsizeH, original.PixelFormat);
Graphics largeGraphics = Graphics.FromImage(largeImage);
largeGraphics.SmoothingMode = SmoothingMode.HighQuality;
largeGraphics.CompositingQuality = CompositingQuality.HighQuality;
largeGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle largeRectangle = new Rectangle(0, 0, bigsizeW
, bigsizeH);
largeGraphics.DrawImage(original, largeRectangle);
MemoryStream stream = new MemoryStream();
largeImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
if (!fTPHelper.Upload(stream, big1))
{
//throw "上传大图失败";
}
//中图
System.Drawing.Image mediumImage = new Bitmap(mediumsizeW, mediumsizeH);
float am = Math.Min(originalH, originalW);
float xm = (originalW - am) / 2;
float ym = (originalH - am) / 2;
Graphics mediumGraphic = Graphics.FromImage(mediumImage);
mediumGraphic.SmoothingMode = SmoothingMode.HighQuality;
mediumGraphic.CompositingQuality = CompositingQuality.HighQuality;
mediumGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle mediumRectangle = new Rectangle(0, 0, mediumsizeW
, mediumsizeH);
mediumGraphic.DrawImage(original, mediumRectangle, xm, ym, am, am, GraphicsUnit.Pixel);
stream = new MemoryStream();
mediumImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
if (!fTPHelper.Upload(stream, medium1))
{
//throw new BizException("上传中图失败");
}
//小图
System.Drawing.Image smallImage = new Bitmap(smallsizeW, smallsizeH);
float a = Math.Min(originalH, originalW);
float x = (originalW - a) / 2;
float y = (originalH - a) / 2;
Graphics smallGraphic = Graphics.FromImage(smallImage);
smallGraphic.SmoothingMode = SmoothingMode.HighQuality;
smallGraphic.CompositingQuality = CompositingQuality.HighQuality;
smallGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle smallRectangle = new Rectangle(0, 0, smallsizeW
, smallsizeH);
smallGraphic.DrawImage(original, smallRectangle, x, y, a, a, GraphicsUnit.Pixel);
stream = new MemoryStream();
smallImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
if (!fTPHelper.Upload(stream, small1))
{
//throw new BizException("上传小图失败");
}
//色图
System.Drawing.Image colorImage = new Bitmap(colorsizeW, colorsizeH);
a = Math.Min(originalH, originalW);
x = (originalW - a) / 2;
y = (originalH - a) / 2;
Graphics colorGraphic = Graphics.FromImage(colorImage);
colorGraphic.SmoothingMode = SmoothingMode.HighQuality;
colorGraphic.CompositingQuality = CompositingQuality.HighQuality;
colorGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle colorRectangle = new Rectangle(0, 0, colorsizeW
, colorsizeH);
colorGraphic.DrawImage(original, colorRectangle, x, y, a, a, GraphicsUnit.Pixel);
stream = new MemoryStream();
colorImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
if (!fTPHelper.Upload(stream, color1))
{
//throw new BizException("上传色图失败");
}
//原图
System.Drawing.Image originalImage = new Bitmap(originalW, originalH);
a = Math.Min(originalH, originalW);
x = (originalW - a) / 2;
y = (originalH - a) / 2;
Graphics originalGraphic = Graphics.FromImage(originalImage);
originalGraphic.SmoothingMode = SmoothingMode.HighQuality;
originalGraphic.CompositingQuality = CompositingQuality.HighQuality;
originalGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle originalRectangle = new Rectangle(0, 0, originalW
, originalH);
originalGraphic.DrawImage(original, originalRectangle, x, y, a, a, GraphicsUnit.Pixel);
stream = new MemoryStream();
originalImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
if (!fTPHelper.Upload(stream, original1))
{
//throw new BizException("上传原图失败");
}
//释放资源
largeImage.Dispose();
largeGraphics.Dispose();
mediumImage.Dispose();
mediumGraphic.Dispose();
smallImage.Dispose();
smallGraphic.Dispose();
original.Dispose();
//productInfo.BasicInfo.MultiPicNum++;
//ProductManager.GetInstance().UpdateBasicInfo(productInfo.BasicInfo);
StringBuilder str2 = new StringBuilder();
//ProductInfo productInfo2 = Icson.BLL.Basic.ProductManager.GetInstance().LoadProduct(_productID);
//for (int i = 1; i <= productInfo2.BasicInfo.MultiPicNum; i++)
//{
// if (i == 1)
// {
// str2.Append(
// "<a onclick=lookBig2('" +
// i + "') style='cursor:pointer;'>" + string.Format("<image width='60px' height='60px' src='{0}' title='" + productInfo.BasicInfo.ProductName +
// "' style='padding-right:5px;cursor:pointer; margin:2px;' />",
// AppConfig.PictureServerBigPath + _productID + ".jpg?time=" + DateTime.Now.ToString()) + "</a><a style='cursor:pointer;' onclick=DeletePicture('" + _productID + "','" + i + "') >删除</a>");
// }
// else
// {
// str2.Append(
// "<a onclick=lookBig2('" +
// i + "') style='cursor:pointer;'>" + string.Format("<image width='60px' height='60px' src='{0}' title='" + productInfo.BasicInfo.ProductName +
// "' style='padding-right:5px;cursor:pointer;margin:2px;' />",
// AppConfig.PictureServerBigPath + (i - 1) + "_" + _productID + ".jpg?time=" + DateTime.Now.ToString()) + "</a><a style='cursor:pointer;' onclick=DeletePicture('" + _productID + "','" + i + "') >删除</a>");
// }
//}
result = str2.ToString();
}
catch (Exception ex)
{
result = "error";
}
context.Response.ContentType = "text/plain";
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
}
-----------------------------------------------
public class FTPHelper
{
private string ftpUri; //ftp服务器地址
private string ftpName; //ftp帐户
private string ftpPwd; //ftp密码
private FtpWebRequest ftpRequest; //请求
private FtpWebResponse ftpResponse; //响应
public FTPHelper(string uri, string name, string password)
{
this.ftpUri = uri;
this.ftpName = name;
this.ftpPwd = password;
}
/// <summary>
/// 连接类
/// </summary>
/// <param name="uri">ftp地址</param>
private void Conn(string uri)
{
ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
//登录ftp服务器,ftpName:账户名,ftpPwd:密码
ftpRequest.Credentials = new NetworkCredential(ftpName, ftpPwd);
ftpRequest.UseBinary = true; //该值指定文件传输的数据类型。
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName">文件名</param>
public void DeleteFileName(string fileName)
{
string uri = ftpUri + fileName;
Conn(uri);
try
{
ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpResponse.Close();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 上传文件,使用FTPWebRequest、FTPWebResponse实例
/// </summary>
/// <param name="uri">ftp地址</param>
/// <param name="fileName">文件名</param>
/// <param name="fileData">文件内容</param>
/// <param name="msg">传出参数,返回传输结果</param>
public void UploadFile(string uri, string fileName, byte[] fileData, out string msg)
{
string URI = uri.EndsWith("/") ? uri : uri + "/";
URI += fileName;
//连接ftp服务器
Conn(URI);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.ContentLength = fileData.Length; //上传文件时通知服务器文件的大小
try
{
//将文件流中的数据(byte[] fileData)写入请求流
using (Stream ftpstream = ftpRequest.GetRequestStream())
{
ftpstream.Write(fileData, 0, fileData.Length);
}
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); //响应
msg = ftpResponse.StatusDescription; //响应状态
ftpResponse.Close();
}
catch (Exception exp)
{
msg = "Failed to upload:" + exp.Message;
throw new BizException(exp.Message);
}
}
/// <summary>
/// 上传文件,使用WebClient类
/// </summary>
/// <param name="uri">ftp地址</param>
/// <param name="fileName">文件名</param>
/// <param name="fileData">文件内容</param>
/// <param name="msg">传出参数,输出传输结果</param>
public void UploadFileByWebClient(string uri, string fileName, byte[] fileData, out string msg)
{
string URI = uri.EndsWith("/") ? uri : uri + "/";
URI += fileName;
try
{
WebClient client = new WebClient();
//登录FTP服务
client.Credentials = new NetworkCredential(ftpName, ftpPwd);
client.UploadData(URI, "STOR", fileData); //指定为ftp上传方式
msg = "上传成功!";
}
catch (Exception exp)
{
msg = "Failed to upload:" + exp.Message;
throw new BizException(exp.Message);
}
}
/// <summary>
/// 下载文件,使用FTPWebRequest、FTPWebResponse实例
/// </summary>
/// <param name="uri">ftp地址</param>
/// <param name="destinationDir">目标文件存放地址</param>
/// <param name="msg">传出参数,返回传输结果</param>
public void DownloadFile(string uri, string destinationDir, out string msg)
{
string fileName = Path.GetFileName(uri);
string destinationPath = Path.Combine(destinationDir, fileName);
try
{
//连接ftp服务器
Conn(uri);
using (FileStream outputStream = new FileStream(destinationPath, FileMode.OpenOrCreate))
{
using (ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
{
//将响应流中的数据写入到文件流
using (Stream ftpStream = ftpResponse.GetResponseStream())
{
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
}
msg = ftpResponse.StatusDescription;
}
}
}
catch (Exception exp)
{
msg = "Failed to download:" + exp.Message;
throw new BizException(exp.Message);
}
}
/// <summary>
/// 文件下载,使用WebClient类
/// </summary>
/// <param name="uri">ftp服务地址</param>
/// <param name="destinationDir">存放目录</param>
public void DownloadFileByWebClient(string uri, string destinationDir)
{
string fileName = Path.GetFileName(uri);
string destinationPath = Path.Combine(destinationDir, fileName);
try
{
WebClient client = new WebClient();
client.Credentials = new NetworkCredential(this.ftpName, this.ftpPwd);
byte[] responseData = client.DownloadData(uri);
using (FileStream fileStream = new FileStream(destinationPath, FileMode.OpenOrCreate))
{
fileStream.Write(responseData, 0, responseData.Length);
}
}
catch (Exception exp)
{
throw new BizException(exp.Message);
}
}
/// <summary>
/// 遍历文件
/// </summary>
public ArrayList GetListDirectoryDetails()
{
ArrayList fileInfo = new ArrayList();
try
{
Conn(ftpUri);
//获取 FTP 服务器上的文件的详细列表的 FTP LIST 协议方法
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); //响应
}
catch (System.Net.WebException e)
{
ErrorLog.GetInstance().Write(e.Message);
ErrorLog.GetInstance().Write(e.Message);
throw new BizException(e.Message);
}
catch (System.InvalidOperationException e)
{
ErrorLog.GetInstance().Write(e.Message);
throw new BizException(e.Message);
}
using (Stream responseStream = ftpResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string line = reader.ReadLine();
while (line != null)
{
fileInfo.Add(line);
line = reader.ReadLine();
}
}
}
}
catch (Exception exp)
{
ErrorLog.GetInstance().Write(exp.Message);
throw new BizException(exp.Message);
}
return fileInfo;
}
/// <summary>
/// 上传图片
/// </summary>
/// <param name="mstr"></param>
/// <param name="ftpUri"></param>
/// <returns></returns>
public bool Upload(MemoryStream mstr, string ftpUri)
{
try
{
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.credentials/ = new NetworkCredential(ftpName, ftpPwd);
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.method/ = WebRequestMethods.Ftp.UploadFile;
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.usebinary/ = true;
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.usepassive/ = true;
using (Stream stream = http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.getrequeststream/())
{
byte[] bytes = mstr.ToArray();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
mstr.Close();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool Upload(byte[] mstr, string ftpUri)
{
try
{
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri);
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.credentials/ = new NetworkCredential(ftpName, ftpPwd);
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.method/ = WebRequestMethods.Ftp.UploadFile;
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.usebinary/ = true;
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.usepassive/ = true;
using (Stream stream = http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.getrequeststream/())
{
stream.Write(mstr, 0, mstr.Length);
stream.Close();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 重命名文件
/// </summary>
/// <param name="fileName">文件名</param>
public bool RenameFileName(string fileName, string reNameFileName)
{
bool result = true;
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(reNameFileName);
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.credentials/ = new NetworkCredential(ftpName, ftpPwd);
try
{
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.method/ = WebRequestMethods.Ftp.Rename;
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.renameto/ = fileName;
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.usebinary/ = true;
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.usepassive/ = true;
ftpResponse = (FtpWebResponse)ftp.GetResponse();
Stream ftpStream = ftpResponse.GetResponseStream();
ftpStream.Close();
ftpResponse.Close();
}
catch (Exception exp)
{
result = false;
}
return result;
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName">文件名</param>
public bool DeleteFile(string fileName)
{
bool result = true;
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(fileName);
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.credentials/ = new NetworkCredential(ftpName, ftpPwd);
try
{
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.method/ = WebRequestMethods.Ftp.DeleteFile;
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.usebinary/ = true;
http://www.cnblogs.com/tianxiang2046/admin/ftp://ftp.usepassive/ = true;
ftpResponse = (FtpWebResponse)ftp.GetResponse();
Stream ftpStream = ftpResponse.GetResponseStream();
ftpStream.Close();
ftpResponse.Close();
}
catch (Exception exp)
{
result = false;
}
return result;
}
/// <summary>
/// Summary description for BizException.
/// </summary>
[Serializable]
public class BizException : ApplicationException
{
private string MsgCn;
private string MsgEn;
public BizException() { }
public BizException(string message)
: base(message)
{
MsgCn = message;
}
public BizException(string messageCn, string messageEn)
: base(messageCn)
{
MsgCn = messageCn;
MsgEn = messageEn;
}
//public BizException(string message, Exception e) : base(message, e) {}
}
}
-----------------------------------------------------------
public class ErrorLog
{
private static object locker = new object();
private ErrorLog()
{
}
private static ErrorLog log = new ErrorLog();
/// <summary>
/// 返回日志实例
/// </summary>
/// <returns></returns>
public static ErrorLog GetInstance()
{
lock (locker)
{
if ("c:\\Temp\\IcsonError\\" != null)
{
errorLogFolder = "c:\\Temp\\IcsonError\\";
try
{
if (!Directory.Exists(errorLogFolder))
Directory.CreateDirectory(errorLogFolder);
}
catch (Exception exp)
{
Console.Write(exp.ToString());
}
}
string str = DateTime.Now.ToString("yyyy-MM-dd");
errorLogFile = errorLogFolder + str + ".txt";
try
{
if (File.Exists(errorLogFile) == false)
{
FileStream stream = File.Create(errorLogFile);
stream.Close();
}
}
catch (Exception exp)
{
Console.Write(exp.ToString());
}
}
return log;
}
/// <summary>
/// write log to file
/// </summary>
/// <param name="message"></param>
public void Write(string message)
{
lock (locker)
{
StreamWriter writer = null;
try
{
writer = new StreamWriter(errorLogFile, true, System.Text.Encoding.Default);
StringBuilder sb = new StringBuilder(500);
sb.Append(DateTime.Now.ToString()).Append(DateTime.Now.Ticks.ToString()).Append("\r\n");
sb.Append(message).Append("\r\n");
sb.Append("---------------------------------------").Append("\r\n");
writer.Write(sb.ToString());
}
catch (IOException ioe)
{
Console.WriteLine(ioe.ToString());
}
finally
{
try
{
if (writer != null)
writer.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
private static string errorLogFolder = @"c:\Temp\IPP3Log\";
private static string errorLogFile;
}