asp.net custom controls implement no refresh upload pictures, immediately display thumbnails, save picture thumbnails _ Practical Tips

Source: Internet
Author: User

As shown in figure:

Click to browse, select the picture, the right display picture

First step:

Create Ctfileupload.ascx

Copy Code code as follows:

<%@ control language= "C #" autoeventwireup= "true" codefile= "CtFileUpLoad.ascx.cs"
inherits= "Webparts_ctfileupload"%>
<table cellpadding= "0" cellspacing= "0" >
<tr>
<td>
<iframe src= "/webparts/fileupload.aspx?<%=parsvalue%>" width= "240px" height= "22px" frameborder= "0" Scrolling= "No" ></iframe>
</td>
<td>
<asp:textbox runat= "Server" id= "Tbfilename" style= "Display:none" ></asp:TextBox>
<div id= "dvimg" runat= "style=" Position:absolute; margin-left:50px; " >
</div>
</td>
</tr>
</table>
<script language= "JavaScript" >
function <%=clientid%>callloaded ()
{
<% =onloaded%>;
}
</script>

Copy Code code as follows:

Using System;
Using System.Collections;
Using System.Configuration;
Using System.Data;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.HtmlControls;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Drawing;
public partial class WebParts_CtFileUpLoad:System.Web.UI.UserControl
{
public bool Autofilename
{
Get
{
Object OB = Viewstate[clientid + "Autofilename"];
if (ob = null)
OB = TRUE;
return (BOOL) OB;
}
Set
{
Viewstate[clientid + "Autofilename"] = value;
}
}
public string Uploadpath
{
Get
{
Object OB = Viewstate[clientid + "Uploadpath"];
if (ob = null)
OB = "Uploadfiles";
Return OB. ToString ();
}
Set
{
Viewstate[clientid + "Uploadpath"] = value;
}
}
public string onloaded
{
Get
{
Object OB = Viewstate[clientid + "onloaded"];
if (ob = null)
OB = "";
Return OB. ToString ();
}
Set
{
Viewstate[clientid + "onloaded"] = value;
}
}
public string Supportextension
{
Get
{
Object OB = Viewstate[clientid + "supportextension"];
if (ob = null)
{
OB = "Gif|png|jpeg|jpg";
}
Return OB. ToString ();
}
Set
{
Viewstate[clientid + "supportextension"] = value. Replace (".", "");
}
}
public bool Showimg
{
Get
{
Object OB = Viewstate[clientid + "showimg"];
if (ob = null)
OB = TRUE;
return (BOOL) OB;
}
Set
{
if ((bool) value)
dvimg.style["display"] = "block";
Else
dvimg.style["Display" = "none";
}
}
public string FileName
{
Get
{
return tbfilename.text;
}
}
protected string parsvalue = "";
protected void Page_Load (object sender, EventArgs e)
{
Parsvalue = "Autofilename=" + autofilename.tostring () + "&supportextension=" + supportextension + "&UpLoadPath=" + Uploadpath
+ "&id=" + ClientID;
}
}

Step Two:
Create fileupload.aspx
Copy Code code as follows:

<%@ Page language= "C #" autoeventwireup= "true" codefile= "FileUpLoad.aspx.cs" inherits= "Webparts_fileupload"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<body style= "margin:0px;" >
<form id= "Form1" runat= "Server" >
<div>
<asp:fileupload runat= "Server" id= "FileUpload1" onchange= "Upload" (this); "/>
<asp:button runat= "Server" id= "Btup" style= "Display:none" onclick= "Btup_click"/>
</div>
</form>
</body>
<script language= "JavaScript" >
function upload (OB)
{
var expstr=/.* (<%=SupportExtension%>) $/i;
if (!expstr.test (Ob.value))
{
Alert ("Upload file type is incorrect.) \ n (supporting file type:<%=supportextension%>) ");
}
Else
{
var Btup=document.getelementbyid ("<%=btup.clientid%>");
Btup.click ();
}
}
</script>

Copy Code code as follows:

Using System;
Using System.Collections;
Using System.Configuration;
Using System.Data;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.HtmlControls;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Drawing;
Using System.IO;
public partial class WebParts_FileUpLoad:System.Web.UI.Page
{
protected string supportextension = "";
protected string uploadpath = "";
protected bool Autofilename;
protected string parentid = "";
protected void Page_Load (object sender, EventArgs e)
{
Supportextension = request.querystring["Supportextension"];
Uploadpath = request.querystring["Uploadpath"];
Autofilename = bool. Parse (request.querystring["Autofilename"). ToString ());
ParentID = request.querystring["ID"]. ToString ();
}
protected void Btup_click (object sender, EventArgs e)
{
Boolean FileOK = false;
if (fileupload1.hasfile)
{
String fileextension =
System.IO.Path.GetExtension (Fileupload1.filename). ToLower ();
string[] allowedextensions = Supportextension.split (new string[] {"|"}, stringsplitoptions.removeemptyentries);
for (int i = 0; i < allowedextensions.length; i++)
{
if (fileextension = = "." + Allowedextensions[i])
{
FileOK = true;
}
}
if (FileOK)
{
String path = "";
String name = "";
String spath = "";
if (autofilename)
{
Name = DateTime.Now.Ticks.ToString () + System.IO.Path.GetExtension (fileupload1.filename). ToLower ();
}
Else
{
name = Fileupload1.filename;
}
spath = Request.physicalapplicationpath + "\" + Uploadpath + "\";
Path = spath + name; Picture Address
string fileName = name; Filename
String filename_s = "S_" + name; Thumbnail file name
Try
{
FileInfo file = new FileInfo (name);
string filecontenttype = FileUpload1.PostedFile.ContentType;
String name = fileupload1.postedfile.filename;//Client file path
String filename_sy = "Sy_" + file. Name; Watermark image file name (text)
String FILENAME_SYP = "Syp_" + file. name;//watermark image file name (picture)
String webfilepath = Server.MapPath (Uploadpath + "\" + fileName);
String webfilepath_s = Server.MapPath (Uploadpath + "\" + filename_s);
String Webfilepath = spath + filename;//server-side file path
String webfilepath_s = spath + filename_s;//server-side thumbnail path

if (! File.exists (Webfilepath))
{
if (FileUpload1.PostedFile.ContentLength < 2 * 1024 * 1024)///If the picture is less than 2M
{
Try
{
Fileupload1.saveas (path); Save a file using the SaveAs method
System.Drawing.Image Image = System.Drawing.Image.FromFile (path);
if (image. Width > 800 | | Image. Height > 600)
{
Makethumbnail (Webfilepath, webfilepath_s, M, N, "W"); How to generate thumbnails
}
Else
{
Makethumbnail (Webfilepath, webfilepath_s, 230, "W"); How to generate thumbnails
}
Image. Dispose ();
Addshuiyinword (Webfilepath, Webfilepath_sy); Save Watermark Text Picture
Addshuiyinpic (Webfilepath, WEBFILEPATH_SYP, WEBFILEPATH_SYPF);//Save the picture after you add the watermark picture
Makethumbnail (Webfilepath, webfilepath_s, RPM, "W"); How to generate thumbnails

Page.registerclientscriptblock ("succcess", @ "<script>
Alert (' upload success ');
Parent.document.getElementById (' "+ ParentID +" _ "+" Tbfilename "+ @"). Value= ' + filename_s + @ ';
</script> ");
}
catch (Exception ex)
{
Page.registerclientscriptblock (' err ', ' <script>alert (' Hint: File upload failed, reason for failure:: "+ ex. Message + "');</script>");
}
}
Else
{
Page.registerclientscriptblock ("Err", "<script>alert (' Hint: picture cannot be greater than 2M ');</script>");
}
}
Else
{
This. Page.registerclientscriptblock ("Err", "<script>alert (' picture repeats ');</script>");
}
}
catch (System.Exception err)
{
This. Page.registerclientscriptblock ("Err", "<script>alert" + Err.) Message + "');</script>");
}
Try
{
Bitmap bmp = new Bitmap (path);
int width = 0, height = 0;
int dvalue = 200;
if (BMP. Width < Dvalue & BMP. Height < 200)
{
width = bmp. Width;
Height = bmp. Height;
}
else if (BMP. Width > BMP. Height)
{
width = dvalue;
Height = Dvalue * (BMP. Width/bmp. Height);
}
Else
{
Height = dvalue;
width = dvalue * (BMP. Height/bmp. Width);
}
This. Page.registerclientscriptblock ("Show", @ "<script>
Parent. Varvalue= ' "+ Uploadpath +"/"+ filename_s +" '; "+
"Parent." + ParentID + "callloaded ();" +
"Parent.document.getElementById ('" + ParentID + "_" + "dvimg" + @ "). Innerhtml=" "+
" "+ @" "";
</script> ");
Bmp. Dispose ();
}
Catch
{
}
Finally
{
Determine if the file exists, or delete the picture if it exists
if (file.exists (path))
{
Delete User Client upload picture, server only save thumbnail image
File.delete (path);
}
}
}
Else
{
This. Page.registerclientscriptblock ("Err", "<script>alert (' Error ');</script>");
}
}
}
<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 void 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 format
Bitmap. Save (Thumbnailpath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
Throw e;
}
Finally
{
Originalimage.dispose ();
Bitmap. Dispose ();
G.dispose ();
}
}
<summary>
Add a text watermark to a picture
</summary>
<param name= "Path" > Original server picture Path </param>
<param name= "Path_sy" > generated image path with text watermark </param>
protected void Addshuiyinword (String Path, String path_sy)
{
String addtext = "Http://www.jb51.net";
System.Drawing.Image Image = System.Drawing.Image.FromFile (Path);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage (image);
G.drawimage (image, 0, 0, image. Width, image. Height);
System.Drawing.Font f = new System.Drawing.Font ("Verdana", 16);
System.Drawing.Brush B = new System.Drawing.SolidBrush (System.Drawing.Color.Blue);
g.DrawString (AddText, F, B, 15, 15);
G.dispose ();
Image. Save (Path_sy);
Image. Dispose ();
}
<summary>
Generate a picture watermark on a picture
</summary>
<param name= "Path" > Original server picture Path </param>
<param name= "PATH_SYP" > Image path with picture watermark </param>
<param name= "PATH_SYPF" > Watermark image Path </param>
protected void Addshuiyinpic (String Path, String Path_syp, String path_sypf)
{
System.Drawing.Image Image = System.Drawing.Image.FromFile (Path);
System.Drawing.Image copyimage = System.Drawing.Image.FromFile (PATH_SYPF);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage (image);
G.drawimage (Copyimage, new System.Drawing.Rectangle) (image. Width-copyimage.width, image. Height-copyimage.height, Copyimage.width, Copyimage.height), 0, 0, copyimage.width, Copyimage.height, System.Drawing.GraphicsUnit.Pixel);
G.dispose ();
Image. Save (PATH_SYP);
Image. Dispose ();
}
}

Property:
Supportextension custom upload format, with "|" Separated
Uploadpath custom upload to server folder;
Autofilename ture indicates that the file name is automatically generated based on time, does not repeat, False indicates the original picture name, and repeats will overwrite.

Reprint please indicate the source
2009-12-24 18:39:27 by Zi Kojia

Related Article

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.