Analog QQ Mood Picture Upload Preview Example _ Practical skills

Source: Internet
Author: User
Tags httpcontext jquery file upload
For security performance considerations, the current JS end does not support to obtain a local picture preview, just do a similar to the QQ mood of the release box, looking for a lot of jquery plug-ins, few can meet the demand, so they use Swfuplad to achieve this picture upload preview.

First stick to the following plug-ins, in other pictures upload function you may be able to use.

1, jQuery File Upload

Demo Address: http://blueimp.github.io/jQuery-File-Upload/
The advantage is to use jquery to upload pictures asynchronously, controllable, can be customized according to their own needs;
The disadvantage is that in some browsers, such as IE9, do not support picture preview, picture selection box does not support multiple file selection (This is why I abandoned it);

2, Cfupdate

Demo Address: http://www.access2008.cn/update/
Advantages: The use of js+flash implementation, compatible with all browsers, the advantages of the interface effect can also support the bulk upload, support preview, progress bar, delete and other functions, as a picture of the upload control very useful;
Disadvantages: Custom-type Plug-ins, can only modify the color, the style has been fixed dead;

3, SWFUpload

Download Address: http://code.google.com/p/swfupload/
Chinese document help address: http://www.phptogether.com/swfuploadoc/#uploadError
This article is used in this plug-in, using the Flash+jquery implementation, you can change the button and a variety of styles, monitoring events are also full.

The following source code and design ideas, the main function points include:
1, the image upload preview (first upload the picture to the server, and then return to the address preview, now put aside HTML5 more reliable preview way)
2, the production of thumbnails (such as proportional scaling after the interception of the middle area as a thumbnail, similar to the practice of QQ space, but seemingly QQ space to join the face recognition function)

Here is a screenshot of this implementation:

1, Thumbnail.cs

Copy Code code as follows:

public class Thumbnial
{
<summary>
Generate thumbnails
</summary>
<param name= "Imgsource" > Original picture </param>
<param name= "Newwidth" > Thumbnail width </param>
<param name= "newheight" > Thumbnail height </param>
<param name= "Iscut" > Cropping (with center point) </param>
<returns></returns>
public static Image GetThumbnail (System.Drawing.Image imgsource, int newwidth, int newheight, BOOL iscut)
{
int rwidth = 0; Width of equal scale after scaling
int rheight = 0; Height after equal scale scaling
int swidth = Imgsource.width; Original picture width
int sheight = Imgsource.height; Original picture height
Double Wscale = (double) swidth/newwidth; Wide scale
Double Hscale = (double) sheight/newheight; High proportion
Double scale = Wscale < Hscale? Wscale:hscale;
Rwidth = (int) math.floor (Swidth/scale);
Rheight = (int) math.floor (Sheight/scale);
Bitmap thumbnail = new Bitmap (rwidth, rheight);
Try
{
If it is to intercept the original image, and the original ratio is less than the rectangular box to be intercepted, then keep the original
if (!iscut && scale <= 1)
{
return imgsource;
}

using (Graphics tgraphic = graphics.fromimage (thumbnail))
{
Tgraphic.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; * New Way * *
Rectangle rect = new Rectangle (0, 0, rwidth, rheight);
Rectangle rectsrc = new Rectangle (0, 0, swidth, sheight);
Tgraphic.drawimage (Imgsource, rect, RECTSRC, GraphicsUnit.Pixel);
}

if (!iscut)
{
return thumbnail;
}
Else
{
int xmove = 0; Offset right (cropping)
int ymove = 0; Offset downward (cropping)
Xmove = (rwidth-newwidth)/2;
Ymove = (rheight-newheight)/2;
Bitmap final_image = new Bitmap (newwidth, newheight);
using (Graphics fgraphic = Graphics.fromimage (final_image))
{
Fgraphic.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; * New Way * *
Rectangle rect1 = new Rectangle (0, 0, newwidth, newheight);
Rectangle rectSrc1 = new Rectangle (Xmove, Ymove, Newwidth, newheight);
Fgraphic.drawimage (thumbnail, rect1, RectSrc1, GraphicsUnit.Pixel);
}

Thumbnail. Dispose ();

return final_image;
}
}
catch (Exception e)
{
return new Bitmap (Newwidth, newheight);
}
}
}

2, Picture upload processing program upload.ashx
Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Drawing;

Namespace Mood
{
<summary>
Summary description of Upload
</summary>
public class Upload:ihttphandler
{
Image thumbnail;

public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
Try
{
String id = System.Guid.NewGuid (). ToString ();
Httppostedfile jpeg_image_upload = context. request.files["Filedata"];
Image original_image = System.Drawing.Image.FromStream (jpeg_image_upload. InputStream);
Original_image. Save (System.Web.HttpContext.Current.Server.MapPath ("~/files/" + ID + ". jpg"));
int target_width = 200;
int target_height = 150;
String path = "Files/files200/" + ID + ". jpg";
String savethumbnailpath = System.Web.HttpContext.Current.Server.MapPath ("~/" + path);
thumbnail = Thumbnial.getthumbnail (original_image, Target_width, Target_height, true);
Thumbnail. Save (Savethumbnailpath);
Context. Response.Write (path);
}
catch (Exception e)
{
If any kind of the error occurs return a Internal Server error
Context. Response.statuscode = 500;
Context. Response.Write ("error occurred during upload!");
}
Finally
{
if (thumbnail!= null)
{
Thumbnail. Dispose ();
}
}
}

public bool IsReusable
{
Get
{
return false;
}
}
}
}

3, Front interface mood.aspx
Copy Code code as follows:

<%@ Page language= "C #" autoeventwireup= "true" codebehind= "Mood.aspx.cs" inherits= "Mood.mood"%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<script src= "Swfupload/swfupload.js" type= "Text/javascript" ></script>
<script src= "Jquery-1.7.1.js" type= "Text/javascript" ></script>
<link href= "Style/mood.css" rel= "stylesheet" type= "Text/css"/>
<title></title>
<script type= "Text/javascript" >
$ (). Ready (function () {
Setswf ();
$ ("#btnReply"). Click (function () {
$ ("#divImgs"). Hide ();
});
});

var swfu;
function setswf () {
SWFU = new SWFUpload ({
Backend Settings
Upload_url: "Upload.ashx",
File Upload Settings
File_size_limit: "MB",
File_Types: "*.jpg;*.png;*jpeg;*bmp",
File_types_description: "JPG; PNG; JPEG; BMP ",
File_upload_limit: "0",//Zero means unlimited
File_queue_error_handler:filequeueerror,
File_dialog_complete_handler:filedialogcomplete,
Upload_progress_handler:uploadprogress,
Upload_error_handler:uploaderror,
Upload_success_handler:uploadsuccess,
Upload_complete_handler:uploadcomplete,
Button settings
Button_image_url: "/style/image/4-16.png",
button_placeholder_id: "Divbtn",
Button_width:26,
Button_height:26,

Flash Settings
Flash_url: "/swfupload/swfupload.swf",

Custom_settings: {
Upload_target: "Divfileprogresscontainer"
},

Debug Settings
Debug:false
});
}

File checksum
function Filequeueerror (file, errorcode, message) {
try {
Switch (errorcode) {
Case Swfupload.queue_error. Zero_byte_file:
Alert ("Upload file has errors!") ");
Break
Case Swfupload.queue_error. File_exceeds_size_limit:
Alert ("Upload file exceeds limit (20M)!" ");
Break
Case Swfupload.queue_error. Zero_byte_file:
Case Swfupload.queue_error. Invalid_filetype:
Default
Alert ("File Error!") ");
Break
}
catch (ex) {
This.debug (ex);
}

}

Trigger when file selection is complete
function Filedialogcomplete (numfilesselected, numfilesqueued) {
try {
if (numfilesqueued > 0) {
$ ("#divImgs"). Show ();
for (var i = 0; i < numfilesqueued; i++) {
$ ("#ulUpload"). Append (' <li id= "Li ' + i + '" > </li> ');
}

This.startupload ();
}
catch (ex) {
This.debug (ex);
}
}

The process of the scroll bar is not written for the time being
function uploadprogress (file, bytesloaded) {
}

After each file upload successful processing
function uploadsuccess (file, serverdata) {
try {
var index = file.id.substr (file.id.lastIndexOf ('_') + 1);
$ ("#li" + index). HTML ("");
$ ("#li" + index). html (' ');
index++;

catch (ex) {
This.debug (ex);
}
}

The upload of the next file is triggered when the upload is complete
function Uploadcomplete (file) {
try {
if (This.getstats (). files_queued > 0) {
This.startupload ();
}
catch (ex) {
This.debug (ex);
}
}

Handling when an individual file uploads an error
function Uploaderror (file, errorcode, message) {
var imagename = "Imgerror.png";
try {
var index = file.id.substr (file.id.lastIndexOf ('_') + 1);
$ ("#li" + index). HTML ("");
$ ("#li" + index). html (' ");
index++;
} catch (EX3) {
This.debug (EX3);
}
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<div style= "width:600px;" >
<div class= "Divtxt" >
text box
</div>
<div style= "height:30px; line-height:30px; " >
<div id= "divbtn" style= "float:left; width:26px; height:26px; " >
</div>
<div style= "float:right;" >
<input id= "btnreply" type= "button" value= "published"/>
</div>
</div>
<div id= "Divimgs" style= "border:1px solid #cdcdcd; Display:none; " >
<div>
Upload pictures </div>
<ul id= "Ulupload" class= "Ulupload" >
</ul>
</div>
</div>
</form>
</body>

Using Vs2010 development, the following is the project source address

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.