Use Uploadify to upload images and compress pictures by size in ASP.

Source: Internet
Author: User

$ (document). Ready (function () {$ ('#uploadify'). Uploadify ({onuploadsuccess:function (file, Returndata, response) {vardata = eval ('('+ Returndata +')'); if(Response = =true&& data. Success = ='true') {                        $("Input[name=backimg]"). attr ("value", data. FileName);//data. FileName save path for picture$('#mainForm'). Submit (); } Else{alert (data.                    Message); }                },                'Height': -,                'width': *,                'Uploadlimit':1,                'Queuesizelimit':1,                'Queueid':'Filequeue',                              'removecompleted':false,                'Auto':false,                'Multi':false,                'ButtonText':'Browse Pictures',                'SWF':'@Url. Content ("~/scripts/uploadify/uploadify.swf")',                'Uploader':'@Url. Content ("~/scripts/uploadify/uploadattach.ashx")'            });

The way to upload a picture to the server is UPLOADATTACH.ASHX

 /// <summary>    ///Summary description of Uploadattach/// </summary>     Public classUploadattach:ihttphandler { Public voidProcessRequest (HttpContext context) {Httppostedfile FileData= Context. request.files["FileData"]; stringFloder = context. request["Floder"]; if(FileData! =NULL)            {                Try                {                    //save path after file upload                    stringPath ="~/img/"; stringFilePath =context.                    Server.MapPath (path); if(!directory.exists (FilePath))                    {directory.createdirectory (FilePath); }                    stringSavefilename = Guid.NewGuid (). ToString () +Filedata.filename; stringNewfilepath = FilePath +Savefilename;                    Filedata.saveas (Newfilepath); //Picture Trimming                    varThumbfilepath =Newfilepath.replace (Path.getextension (Newfilepath),". Thumb"+path.getextension (Newfilepath)); Imagekit.makecenterthumbnail (Newfilepath, Thumbfilepath,1602, -); if(File.exists (Newfilepath)) {file.delete (Newfilepath); } context. Response.Write ("{' Success ': ' true ', ' FileName ': '"+ Savefilename.replace (".",". Thumb.") +"'}"); }                Catch(Exception ex) {context. Response.Write ("{' Success ': ' false ', ' Message ': '"+ex. Message+"'}"); }            }            Else{context. Response.Write ("{' Success ': ' false ', ' Message ': ' Please select the file to upload '}"); }        }         Public BOOLisreusable {Get            {                return false; }        }    }

The method of image clipping compression

  Public Static classImagekit { Public Static BOOLMakecenterthumbnail (stringOrigpath,stringDestPath,intWidthintheight) {            Try            {                using(Image image =Image.FromFile (Origpath)) {                    intOriginalWidth =image.                    Width; intOriginalHeight =image.                    Height; DoubleRatio = Math.max ((OriginalWidth/(Double) Width < originalheight/(Double) height)? OriginalWidth/(Double) Width:originalheight/ (Double) Height,1); varCutsize =NewSize (int) Math.Round (Width * ratio,0), (int) Math.Round (height * ratio,0)); intx = (int) Math.Round (Double) (Originalwidth-cutsize.width)/2,0); inty = (int) Math.Round (Double) (Originalheight-cutsize.height)/2,0); ; varBitmap =NewBitmap (width, height); using(varGraphics =graphics.fromimage (bitmap)) {graphics.compositingquality=compositingquality.highquality; Graphics. SmoothingMode=smoothingmode.highquality; Graphics. Interpolationmode=interpolationmode.highqualitybicubic; Graphics.                        Clear (Color.White); varDestrect =NewRectangle (0,0, width, height); varOriginalrect =NewRectangle (x, Y, Cutsize.width, cutsize.height); Graphics.                    DrawImage (image, Destrect, Originalrect, GraphicsUnit.Pixel); }                    #regionwjy20131004 modification//The following code sets the compression quality when the picture is savedEncoderParameters Encoderparams =Newencoderparameters (); Long[] quality =New Long[1]; quality[0] = -; Encoderparameter Encoderparam=NewEncoderparameter (System.Drawing.Imaging.Encoder.Quality, quality); encoderparams.param[0] =Encoderparam; //gets the ImageCodecInfo object that contains information about the built-in image codec.imagecodecinfo[] Arrayici =imagecodecinfo.getimageencoders (); ImageCodecInfo Jpegici=NULL;  for(inti =0; I < arrayici.length;i++)                    {                        if(Arrayici[i]. Formatdescription.equals ("JPEG") ) {Jpegici=Arrayici[i]; //set the JPEG encoding                             Break; }                    }                    if(Jpegici! =NULL) {bitmap.                    Save (DestPath, Jpegici, encoderparams); }                    //bitmap. Save (destpath);                    #endregion                }                return true; }            Catch            {                return false; }        }    }

How to use:

1, first to add a JS reference

<script src= ". /.. /scripts/uploadify/v3.1/jquery.uploadify-3.1.min.js "type=" Text/javascript "></script>
<link href= ". /.. /scripts/uploadify/v3.1/uploadify1.css "rel=" stylesheet "type=" Text/css "/>

2. The button to upload the attachment is displayed on the page:

<div id= "Filequeue" >
</div>
<input type= "File" Name= "uploadify" id= "Uploadify"/>
<input type= "hidden" name= "backimg" value= "/>

Note: The hidden control backimg is the path of the upload file, the file is uploaded after the success of the assignment, so that after the successful form submission can be read from the picture path to upload pictures

3, Form form as shown below

<form id= "mainform" method= "post" action= ' @Url. Action (model.action) ' > </form>

How to invoke the upload image when committing

function Submitbut () {varFileCount = $ ('#fileQueue'). Find ('Div'). length; if(FileCount >0) {                $('#uploadify'). Uploadify ('Upload','*'); } Else {                $('#mainForm'). Submit (); }        }

Use Uploadify to upload images and compress pictures by size in ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.