<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.IO;
using System.Text;
using System.Net;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//Source image path
string _fileNamePath = "";
try
{
_fileNamePath = context.Request.Form["upfile"];
string _savedFileResult = UpLoadFile(_fileNamePath); //Start uploading
context.Response .Write(_savedFileResult);//Return the upload result
}
catch
{
context.Response.Write("0|error|File path error");
}
}
///
/// Save image
/// ///
///
private string UpLoadFile(string fileNamePath)
{
//Picture format
string fileNameExt = fileNamePath.Substring(fileNamePath.IndexOf ('.')).ToLower();
if (!CheckFileExt(fileNameExt)) return "0|error|The picture format is incorrect!";
//Save path
string toFilePath = "ProductUpload /";
//Physical full path
string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
//Check if the path exists, create it if not
if (!Directory.Exists (toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
//Generate a random file name that will be saved
string toFileName = GetFileName();
//Will be Saved full path
string saveFile=toFileFullPath toFileName fileNameExt;
///Create WebClient instance
WebClient myWebClient = new WebClient();
//Set windows network security authentication
myWebClient. Credentials = CredentialCache.DefaultCredentials;
//File to be uploaded
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
//Use the UploadFile method in the following format
myWebClient.UploadFile(saveFile,fileNamePath);
return "1|" toFileName fileNameExt "|Save successfully.";
}
/// < ;summary>
/// Detect image type
///
///
///
Correctly returns True private bool CheckFileExt(string _fileExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ". jpeg" };
for (int i = 0; i < allowExt.Length; i )
{
if (allowExt[i] == _fileExt) { return true; }
}
return false;
}
///
/// Get a random picture name
/// ///
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;
}
}
}