|
Using System;
Using System.Collections;
Using System.Web;
Using System.IO;
Using System.Globalization;
Using Litjson;
public class Upload:ihttphandler
{
Private HttpContext context;
public void ProcessRequest (HttpContext context)
{
Get file name
String Aspxurl = context. Request.Path.Substring (0, context. Request.Path.LastIndexOf ("/") + 1);
File Save directory path
String Savepath = ".. /attached/";
File Save Directory URL
String Saveurl = Aspxurl + ". /attached/";
Define file extensions to allow uploads
Hashtable exttable = new Hashtable ();
Exttable.add ("image", "gif,jpg,jpeg,png,bmp");
Exttable.add ("Flash", "swf,flv");
Exttable.add ("Media", "SWF,FLV,MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF,RM,RMVB");
Exttable.add ("File", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
Maximum file size
int maxSize = 52428800;
This.context = context;
Get files
Httppostedfile Imgfile = context. request.files["Imgfile"];
if (imgfile = null)
{
ShowError ("Please select a file.") ");
}
String Dirpath = context. Server.MapPath (Savepath);
if (! Directory.Exists (Dirpath))
{
ShowError ("Upload directory does not exist.) ");
}
Get file type
String dirname = context. request.querystring["dir"];
if (String.IsNullOrEmpty (dirname)) {
DirName = "image";
}
if (!exttable.containskey (dirname)) {
ShowError ("directory name is not correct.) ");
}
String fileName = imgfile.filename;
String Fileext = path.getextension (fileName). ToLower ();
if (Imgfile.inputstream = null | | imgFile.InputStream.Length > MaxSize)
{
ShowError ("Upload file size exceeds limit.") ");
}
if (String.IsNullOrEmpty (fileext) | | Array.indexof ((((String) exttable[dirname]). Split (', '), fileext.substring (1). ToLower ()) = =-1)
{
ShowError ("The upload file name extension is an disallowed extension.") N only allows the "+ ((String) exttable[dirname]) +" format. ");
}
Create a folder
Dirpath + = dirname + "/";
Saveurl + = dirname + "/";
if (! Directory.Exists (Dirpath)) {
Directory.CreateDirectory (Dirpath);
}
String ymd = DateTime.Now.ToString ("YyyyMMdd", datetimeformatinfo.invariantinfo);
Dirpath + = Ymd + "/";
Saveurl + = Ymd + "/";
if (! Directory.Exists (Dirpath)) {
Directory.CreateDirectory (Dirpath);
}
Generate file name
String NewFileName = DateTime.Now.ToString ("Yyyymmddhhmmss_ffff", datetimeformatinfo.invariantinfo) + Fileext;
The physical address of the file save
String FilePath = Dirpath + newfilename;
Save File
Imgfile.saveas (FilePath);
File relative Address
String FILEURL = Saveurl + newfilename;
Sets the return value returned as a JSON array, preceded by a key, followed by value
Hashtable hash = new Hashtable ();
hash["error"] = 0;
Returns the address of the original artwork
hash["url"] = FILEURL;
/*
You can also set multiple return results, such as the width of the picture, the higher
such as: hash["width"]=100;
*/
To determine which file type to upload
if (context. request.querystring["dir"] = = "image")
{
The width in the request indicates that the picture needs to be processed
if (context. request.querystring["width"]!= null)
{//Thumbnail relative address
String Thumbfilepath = Dirpath + "Thumb" + newfilename;
int Width=convert.toint32 (context. request.querystring["width"]);
int Height=convert.toint32 (context. request.querystring["height"]);
Get the width and height of the original picture
System.Drawing.Image originalimage = System.Drawing.Image.FromFile (FilePath);
int ow = Originalimage.width;
int oh = originalimage.height;
If the size of the original artwork is smaller than the size required by the thumbnail, no processing is done
if (width <= ow && height <= OH)
{
string smillurl = FileUrl;
Returns the address of a thumbnail
hash["Thumurl"] = Smillurl;
}
Else
{
Generate thumbnails
if (Makethumbnail (FilePath, Thumbfilepath, width, height, "HW"))
{
String smillurl = Saveurl + "Thumb" + newfilename;
hash["Thumurl"] = Smillurl;
}
Else
{
ShowError ("Generate thumbnails failed");
}
}
}
}
Context. Response.AddHeader ("Content-type", "text/html; Charset=utf-8 ");
Context. Response.Write (Jsonmapper.tojson (hash));
Context. Response.End ();
}
return error message
private void ShowError (String message)
{
Hashtable hash = new Hashtable ();
hash["Error"] = 1;
hash[' message ' = message;
Context. Response.AddHeader ("Content-type", "text/html; Charset=utf-8 ");
Context. Response.Write (Jsonmapper.tojson (hash));
Context. Response.End ();
}
public bool IsReusable
{
Get
{
return true;
}
}
<summary>
Generate thumbnails
</summary>
<param name= "Originalimagepath" > Source map Path (physical path) </param>
<param name= "Thumbnailpath" > Thumbnail path (physical path) </param>
<param name= "width" > Thumbnail width </param>
<param name= "height" > thumbnail height </param>
<param name= "mode" > How to Generate Thumbnails </param>
public static bool Makethumbnail (string Originalimagepath, string thumbnailpath, int width, int height, string mode)
{
System.Drawing.Image originalimage = System.Drawing.Image.FromFile (Originalimagepath);
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = Originalimage.width;
int oh = originalimage.height;
Switch (mode)
{
Case "HW"://Specify width scaling (possibly distorted)
Break
Case "W"://Specify wide, high proportionally
Toheight = Originalimage.height * width/originalimage.width;
Break
Case "H"://specified high, wide proportional
Towidth = Originalimage.width * height/originalimage.height;
Break
Case "cut"://Specify width trim (not deformed)
if (double) originalimage.width/double originalimage.height > (double) towidth/double toheight)
{
Oh = originalimage.height;
ow = Originalimage.height * towidth/toheight;
y = 0;
x = (Originalimage.width-ow)/2;
}
Else
{
ow = Originalimage.width;
Oh = originalimage.width * height/towidth;
x = 0;
y = (Originalimage.height-oh)/2;
}
Break
Default
Break
}
Create a new BMP picture
System.Drawing.Image bitmap = new System.Drawing.Bitmap (towidth, toheight);
Create a new artboard
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage (bitmap);
Set high quality interpolation method
G.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.High;
Set high quality, low speed rendering smooth degree
G.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
Empty the canvas and fill with a transparent background color
G.clear (System.Drawing.Color.Transparent);
Draws the specified portion of the original picture at the specified location and at the specified size
G.drawimage (Originalimage, New System.Drawing.Rectangle (0, 0, Towidth, toheight),
New System.Drawing.Rectangle (x, Y, Ow, OH),
System.Drawing.GraphicsUnit.Pixel);
Try
{
//save thumbnails in jpg
bitmap. Save (Thumbnailpath, System.Drawing.Imaging.ImageFormat.Jpeg);
return true;
}
catch (System.Exception e)
{
return false;
throw e;
}
Finally
{
Originalimage.dispose ();
Bitmap. Dispose ();
G.dispose ();
}
}
}
The front call is very simple, and here is the post:
Kindeditor.ready (function (K) {
var Uploadbutton = K.uploadbutton ({
Button:k (' #uploadButton ') [0],
Type of file uploaded
FieldName: ' Imgfile ',
Note the following arguments, dir represents the file type, width represents the width of the thumbnail, and height represents the height
URL: '../editer/asp.net/upload_json.ashx?dir=image&width=65&height=61 ',
Afterupload:function (data) {
if (Data.error = = 0) {
Alert (' Picture upload success ');
Take the return value, note the key in the background settings, if you want to take the original value
Take the thumbnail address
var thumurl = K.formaturl (Data.thumurl, ' absolute ');
Take the original address
var url=k.fromurl (data. URL, ' absolute ');
K (' #txtPic '). Val (Thumurl);
} else {
alert (data.message);
}
},
Aftererror:function (str) {
Alert (' Custom error message: ' + str ');
}
});
Uploadbutton.fileBox.change (function (e) {
Uploadbutton.submit ();
});
}); |