using System;
using System.Web;
using System.IO;
using System.Text;
using System.Net;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//源图片路径
string _fileNamePath = "";
try
{
_fileNamePath = context.Request.Form["upfile"];
string _savedFileResult = UpLoadFile(_fileNamePath); //开始上传
context.Response.Write(_savedFileResult);//返回上传结果
}
catch
{
context.Response.Write("0|error|文件路径错误");
}
}
///
/// 保存图片
/// ///
///
private string UpLoadFile(string fileNamePath)
{
//图片格式
string fileNameExt = fileNamePath.Substring(fileNamePath.IndexOf('.')).ToLower();
if (!CheckFileExt(fileNameExt)) return "0|error|图片格式不正确!";
//保存路径
string toFilePath = "ProductUpload/";
//物理完整路径
string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
//检查是否有该路径 没有就创建
if (!Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
//生成将要保存的随机文件名
string toFileName = GetFileName();
//将要保存的完整路径
string saveFile=toFileFullPath +toFileName + fileNameExt;
///创建WebClient实例
WebClient myWebClient = new WebClient();
//设定windows网络安全认证
myWebClient.Credentials = CredentialCache.DefaultCredentials;
//要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
//使用UploadFile方法可以用下面的格式
myWebClient.UploadFile(saveFile,fileNamePath);
return "1|"+toFileName+fileNameExt+"|保存成功.";
}
///
/// 检测图片类型
/// ///
///
正确返回True private bool CheckFileExt(string _fileExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg" };
for (int i = 0; i {
if (allowExt[i] == _fileExt) { return true; }
}
return false;
}
///
/// 得到随机图片名
/// ///
public static string GetFileName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("yyMMddHHmmssff"));
serial.Append(rd.Next(0, 9999).ToString());
return serial.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}