asp.net file upload function (single file, multiple files, custom build thumbnail, watermark) _ Practical skills

Source: Internet
Author: User
Tags save file
Preface
Upload function, is often used by everyone, may be used in every project. There are code for uploading on the web. It's a lot better than the one I wrote. I am also here to share my code.
function Realization Point
1. single File upload;
2. multiple file uploads;
3. For pictures and other types of images, you can customize the generation of thumbnail size;
4. File server Extensions.
mode
The main use is the "template method" design pattern.
The features and advantages of this article
1. Can customize the size of the generated thumbnail, arbitrary definition. For websites like micro-life Sports Outdoor Mall (http://sports.8t8x.com/), Taobao, etc., they need to upload a lot of merchandise pictures, very useful.
2. Disadvantages, I am not very skilled in the namespace of the System.Drawing, the method of generating images is copied from the Internet, I think I get these methods of generating images, not very good.
Code Implementation
1. Interface definition
Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Web;
Namespace Ccnf. Plugin.upload
{
<summary>
Interface for uploading functions
</summary>
<creator>Marc</creator>
public interface Iupload
{
<summary>
Upload a single file.
</summary>
<param name= "SourceFile" ></param>
<returns></returns>
<author>Marc</author>
int SaveAs (Httppostedfile sourcefile);
}
}

2. Abstract Template Method Class
Because of the way the code was inserted, Cnblogs would have an error, so I had to use the original copy method, which might seem uncomfortable.
Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Configuration;
Using System.IO;
Using System.Net;
Using System.Data;
Using System.Drawing;
Using System.Drawing.Imaging;
Using System.Drawing.Drawing2D;
Using System.Web;
Using System.Collections;
Namespace Ccnf. Plugin.upload
{
<summary>
Upload function.
This class provides a general method for uploading.
</summary>
<creator>Marc</creator>
Public abstract class Uploadabstract:iupload
{
#region Constant Properties
<summary>
The file name extension that is allowed to be uploaded.
Multiple file extensions are separated by commas in English.
The default is obtained from the web.config.
</summary>
Private readonly String uploadextention = configurationmanager.appsettings["Uploadextention"];
private string uploadextention = null;
<summary>
The file name extension that is allowed to be uploaded.
Multiple file extensions are separated by commas in English.
The default is obtained from the web.config.
</summary>
public string Uploadextention
{
Get
{
if (string. IsNullOrEmpty (this.uploadextention))
{
if (string. IsNullOrEmpty (uploadextention))
{
throw new Exception ("Uploadextention attribute not configured in Web.config");
}
This.uploadextention = uploadextention;
}
return this.uploadextention;
}
Set
{
This.uploadextention = value;
}
}
<summary>
The maximum size of a single file that is allowed to be uploaded.
The unit is K.
The default is obtained from the web.config.
</summary>
Private readonly int uploadlength = convert.toint16 (configurationmanager.appsettings["uploadlength"));
private int uploadlength = 0;
<summary>
The maximum size of a single file that is allowed to be uploaded.
Unit is.
The default is obtained from the web.config.
</summary>
public int Uploadlength
{
Get
{
if (this.uploadlength = 0)
{
This.uploadlength = Uploadlength;
}
return this.uploadlength;
}
Set
{
This.uploadlength = value;
}
}
<summary>
The physical disk on which the uploaded files are to be saved.
This value is a strict physical folder path. such as: E:\CCNF\
Note: You must have a letter.
This belongs to the extended Picture Server data store.
The default is obtained from the web.config.
</summary>
Private readonly String uploadphysicalpath = configurationmanager.appsettings["Uploadphysicalpath"];
private string uploadphysicalpath = null;
<summary>
The physical disk on which the uploaded files are to be saved.
This value is a strict physical folder path. such as: E:\CCNF\
Note: You must have a letter.
This property is used to extend the picture server data store.
The default is obtained from the web.config.
</summary>
public string Uploadphysicalpath
{
Get
{
if (string. IsNullOrEmpty (This.uploadphysicalpath))
{
if (string. IsNullOrEmpty (Uploadphysicalpath))
{
throw new Exception ("Uploadphysicalpath attribute not configured in Web.config");
}
This.uploadphysicalpath = Uploadphysicalpath;
}
return this.uploadphysicalpath;
}
Set
{
This.uploadphysicalpath = value;
}
}
#endregion
#region Enumeration
<summary>
Watermark Type
</summary>
public enum Watermarktypeenum
{
<summary>
Text watermark
</summary>
String = 1,
<summary>
Picture watermark
</summary>
Image = 2
}
<summary>
Upload Results
</summary>
protected enum Uploadresultenum
{
<summary>
An object to upload is not specified
</summary>
Uploadedobjectisnull =-9,
<summary>
File name extension not allowed
</summary>
extentionisnotallowed =-2,
<summary>
File size is not within limits
</summary>
Contentlengthnotwithinthescope =-1,
<summary>
Physical save path for files not configured or unspecified
</summary>
Uploadphysicalpathnospecify =-20,
<summary>
Relative file physical path with no picture watermark specified
</summary>
Imagewartermarkpathnospecify =-30,
<summary>
Text with no watermark specified
</summary>
Stringwatermarknospecify =-31,
<summary>
Failed to upload original file
</summary>
Uploadoriginalfilefailure = 0,
<summary>
Build thumbnail failed
</summary>
Createthumbnailimagefailure =-3,
<summary>
Unknown error
</summary>
Unknownerror =-4,
<summary>
Upload successful
</summary>
Success = 1
}
#endregion
#region Upload Properties
<summary>
Save the folder.
Format such as: Upload\ or images\ or upload\user\. End with \.
No Add letter Allowed
</summary>
public string Savefolder {get; set;}
<summary>
Customize to generate a new folder.
Format like: upload\ or Images\ or upload\2011\10\8\ Wait End with \.
Final folders = Uploadphysicalpath + Savefolder + folder
</summary>
public string Folder {get; set;}
<summary>
Whether to generate watermarks.
Watermark generation is not enabled by default.
</summary>
public bool Ismakewatermark {get; set;}
private int watermarktype = (int) watermarktypeenum.string;
<summary>
How the watermark is generated: string is generated from text and image is generated from the picture.
The default is a text watermark
</summary>
public int Watermarktype
{
Get
{
return this.watermarktype;
}
Set
{
This.watermarktype = value;
}
}
<summary>
Watermark text.
</summary>
public string watermark {get; set;}
<summary>
The location of the watermark picture.
Provides a relative position for a picture watermark.
No disk characters are included.
</summary>
public string Imagewartermarkpath {get; set;}
<summary>
The new file path generated after the upload.
This path is a relative physical path and does not contain a disk character.
</summary>
public string Newfilepath {get; protected set;
<summary>
Generates a thumbnail image of the long width, is a two-dimensional data.
such as: Int a[3,2]={{1,2},{5,6},{9,10}}.
If the file you are uploading is a picture type and you want to generate a thumbnail of the picture, save the long width size you want to generate as an array.
</summary>
Public int[,] picsize {get; set;}
<summary>
The generated picture address corresponds to the length of the two-dimensional array picsize.
If there is an array of incoming picsize, the system returns the Picpath array after the upload is complete.
This array is its final upload path so that the user can perform database operations on this value.
The index position of the resulting picpath corresponds to the Picsize one by one.
This property has been declared as read-only.
</summary>
Public string[] Picpath {get; protected set;}
#endregion
<summary>
Upload a single file
</summary>
<param name= "SourceFile" ></param>
<param name= "Upload" ></param>
<returns></returns>
<author>Marc</author>
public virtual int SaveAs (Httppostedfile sourcefile)
{
int result = 0;
Unknown error
Uploadresultenum uploadresultenum = Uploadresultenum.unknownerror;
if (sourcefile = null)
{
An object to upload is not specified
Uploadresultenum = Uploadresultenum.uploadedobjectisnull;
}
Else
{
Uploadresultenum = Upload (sourcefile);
}
result = (int) uploadresultenum;
return result;
}
<summary>
Uploading files
</summary>
<param name= "SourceFile" ></param>
<returns></returns>
<author>Marc</author>
Private Uploadresultenum Upload (Httppostedfile sourcefile)
{
#region Test before uploading
if (string. IsNullOrEmpty (Uploadphysicalpath))
{
Physical save path for files not configured or unspecified
return uploadresultenum.uploadphysicalpathnospecify;
}
String fileName = SourceFile. FileName;
String fileextention = Path.getextension (fileName);
if (! Checkextention (fileextention))
{
File name extension not allowed
return uploadresultenum.extentionisnotallowed;
}
int filelength = sourcefile. ContentLength;
if (filelength <= 0 | | filelength > UPLOADLENGTH * 1024)
{
File size is not within limits
return uploadresultenum.contentlengthnotwithinthescope;
}
Create a folder to save
String physicalpath = Uploadphysicalpath + Savefolder + Folder;
if (! Directory.Exists (PhysicalPath))
{
Directory.CreateDirectory (PhysicalPath);
}
#endregion
String newfilename = "Ori_" + guid.newguid (). ToString () + fileextention;
New File Relative physical path
String Newfilepath = PhysicalPath + newfilename;
#region Save the original file
if (! Ismakewatermark)//When watermark is not enabled
{
Save File
SourceFile. SaveAs (Newfilepath);
}
else//require watermark to be generated
{
Image bitmap = new System.Drawing.Bitmap (sourcefile. InputStream);
Graphics g = graphics.fromimage (bitmap);
G.interpolationmode = Interpolationmode.high;
G.smoothingmode = Smoothingmode.antialias;
Image fromimg = null;
Try
{
Clear the entire drawing surface and fill with a transparent background color
G.clear (color.transparent);
if (Watermarktype = = (int) watermarktypeenum.string)//Generate a text watermark
{
if (string. IsNullOrEmpty (Watermark))
{
Text with no watermark specified
return uploadresultenum.stringwatermarknospecify;
}
Color color = COLOR.FROMARGB (120, 255, 255, 255);
Brush Brush = new SolidBrush (color);
Automatically scale font size based on interface
int desiredwidth = (int) (bitmap. Width *. 5);
Font font = new Font ("Arial", fontstyle.regular);
SizeF Stringsizef = g.measurestring (watermark, font);
float Ratio = Stringsizef.width/font. sizeinpoints;
int requiredfontsize = (int) (desiredwidth/ratio);
Calculate a picture midpoint position
Font requiredfont = new Font ("Arial", Requiredfontsize, FontStyle.Bold);
Stringsizef = g.measurestring (watermark, Requiredfont);
int x = desiredwidth-(int) (STRINGSIZEF.WIDTH/2);
int y = (int) (bitmap. Height *. 5)-(int) (STRINGSIZEF.HEIGHT/2);
g.DrawString (Watermark, New Font ("Verdana", Requiredfontsize, FontStyle.Bold), Brush, new Point (x, y));
Bitmap. Save (Newfilepath, imageformat.jpeg);
}
else if (Watermarktype = = (int) watermarktypeenum.image)//Generate a picture watermark
{
if (string. IsNullOrEmpty (Imagewartermarkpath))
{
Relative file physical path with no picture watermark specified
return uploadresultenum.imagewartermarkpathnospecify;
}
fromimg = Image.FromFile (Imagewartermarkpath);
G.drawimage (fromimg, New Rectangle (bitmap). Width-fromimg.width, Bitmap. Height-fromimg.height, Fromimg.width, Fromimg.height), 0, 0, fromimg.width, Fromimg.height, GraphicsUnit.Pixel);
Bitmap. Save (Newfilepath, imageformat.jpeg);
}
}
Catch
{
Failed to upload original file
return uploadresultenum.uploadoriginalfilefailure;
}
Finally
{
if (fromimg!= null)
{
Fromimg.dispose ();
}
G.dispose ();
Bitmap. Dispose ();
}
}
#endregion
This. Newfilepath = Newfilepath.replace ("\", "/");
#region generate thumbnails of various specifications
Generate thumbnails of various specifications
if (picsize!= null && picsize.length > 0)
{
int width, height;
ArrayList Picpatharray = new ArrayList ();
for (int i = 0; i < picsize.getlength (0); i++)
{
width = picsize[i, 0];
Height = picsize[i, 1];
Guid Tempguid = Guid.NewGuid ();
Thumbnail name
String thumbnailfilename = PhysicalPath + tempguid.tostring () + "_" + width. ToString () + "X" + height. ToString () + fileextention;
if (! Savethumb (sourcefile, width, height, thumbnailfilename))
{
Build thumbnail failed
return uploadresultenum.createthumbnailimagefailure;
}
Picpatharray.add (Thumbnailfilename.replace ("\", "/"));
}
Picpath = (string[]) Picpatharray.toarray (typeof (String));
}
#endregion
Upload successful
return uploadresultenum.success;
}
<summary>
Generate thumbnails
</summary>
<param name= "SourceFile" ></param>
<param name= "width" > Generate thumbnail widths </param>
<param name= "height" > Build thumbnail Heights </param>
<param name= "Thumbnailfilename" > Thumbnail generation path, the absolute physical path containing the letter. </param>
<returns></returns>
<author>Marc</author>
private bool Savethumb (httppostedfile sourcefile, int width, int height, string thumbnailfilename)
{
BOOL result = FALSE;
Image ori_img = Image.fromstream (sourcefile. InputStream);
int ori_width = ori_img. width;//650
int ori_height = ori_img. height;//950
int new_width = width;//700
int new_height = height;//700
In this case, the formula is as follows:
if (New_width > Ori_width)
{
New_width = Ori_width;
}
if (New_height > Ori_height)
{
New_height = Ori_height;
}
if (double) ori_width/double ori_height > (double) new_width/double new_height)
{
New_height = Ori_height * new_width/ori_width;
}
Else
{
New_width = Ori_width * new_height/ori_height;
}
Image bitmap = new System.Drawing.Bitmap (new_width, new_height);
Graphics g = graphics.fromimage (bitmap);
Try
{
G.smoothingmode = smoothingmode.highquality;
G.interpolationmode = Interpolationmode.high;
G.clear (System.Drawing.Color.Transparent);
G.drawimage (ori_img, New Rectangle (0, 0, New_width, new_height), new Rectangle (0, 0, Ori_width, ori_height), GraphicsUnit . Pixel);
Bitmap. Save (Thumbnailfilename, imageformat.jpeg);
result = true;
}
Catch
{
result = false;
}
Finally
{
if (ori_img!= null)
{
Ori_img. Dispose ();
}
if (bitmap!= null)
{
Bitmap. Dispose ();
}
G.dispose ();
Bitmap. Dispose ();
}
return result;
}
<summary>
Check file name extension
</summary>
<param name= "Extention" ></param>
<returns></returns>
protected bool Checkextention (string extention)
{
BOOL B = false;
String[] Extentions = this. Uploadextention.split (', ');
for (int i = 0; i < extentions. Length; i++)
{
if (extention. ToLower () = = Extentions[i]. ToLower ())
{
B = true;
Break
}
}
return b;
}
<summary>
return upload Results
</summary>
<param name= "Result" > Message set </param>
<returns></returns>
<author>marc</author>
public string Error (int[] result)
{
string s = "";
for (int i = 0; I < result. Length; i++)
{
s + = "First" + (i + 1). ToString () + "Zhang:";
if (Result[i]!= 1)
{
Switch (Result[i])
{
case (int) Uploadresultenum.uploadedobjectisnull:
S + + "unspecified object to upload";
Break
case (int) uploadresultenum.extentionisnotallowed:
S + + "file name extension not allowed";
Break
case (int) Uploadresultenum.contentlengthnotwithinthescope:
s + = "File size is not within the limits";
Break
case (int) Uploadresultenum.uploadphysicalpathnospecify:
S + + "physical Save path for files Not configured or unspecified";
Break
case (int) Uploadresultenum.imagewartermarkpathnospecify:
S + + "does not specify the relative file physical path of the picture watermark";
Break
case (int) Uploadresultenum.stringwatermarknospecify:
S + + "does not specify the text of the watermark";
Break
case (int) Uploadresultenum.uploadoriginalfilefailure:
s + + "upload original file failed";
Break
case (int) Uploadresultenum.createthumbnailimagefailure:
S + + "generation of thumbnail failure";
Break
case (int) Uploadresultenum.unknownerror:
S + + "Unknown error";
Break
Default
Break
}
}
Else
{
s + + "upload success";
}
s + + "; \\r\\n";
}
return s;
}
<summary>
return upload Results
</summary>
<param name= "Result" > Message value, int </param>
<returns></returns>
<author>marc</author>
public string Error (int result)
{
string s = null;
Switch (Result)
{
case (int) Uploadresultenum.uploadedobjectisnull:
S + + "unspecified object to upload";
Break
case (int) uploadresultenum.extentionisnotallowed:
S + + "file name extension not allowed";
Break
case (int) Uploadresultenum.contentlengthnotwithinthescope:
s + = "File size is not within the limits";
Break
case (int) Uploadresultenum.uploadphysicalpathnospecify:
S + + "physical Save path for files Not configured or unspecified";
Break
case (int) Uploadresultenum.imagewartermarkpathnospecify:
S + + "does not specify the relative file physical path of the picture watermark";
Break
case (int) Uploadresultenum.stringwatermarknospecify:
S + + "does not specify the text of the watermark";
Break
case (int) Uploadresultenum.uploadoriginalfilefailure:
s + + "upload original file failed";
Break
case (int) Uploadresultenum.createthumbnailimagefailure:
S + + "generation of thumbnail failure";
Break
case (int) Uploadresultenum.unknownerror:
S + + "Unknown error";
Break
case (int) Uploadresultenum.success:
s + + "upload success";
Break
Default
Break
}
return s;
}
}
}

All of the implementation features are in this template method.
The main definitions are constant properties, enumerations, upload properties, and open method SaveAs (Httppostedfile SourceFile) and methods that return error messages.
3. The implementation of the specific abstract class, very simple, please see
Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Web;
Namespace Ccnf. Plugin.upload
{
<summary>
Uploading files
</summary>
<creator>Marc</creator>
public sealed class Upload:uploadabstract
{
}
}

4. Foreground processing page UPLOAD.ASHX, note is the processing page, ashx file.
Copy Code code as follows:

<%@ WebHandler language= "C #" class= "Upload"%>
Using System;
Using System.Web;
Using System.IO;
public class Upload:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
HttpResponse response = context. Response;
HttpRequest request = context. Request;
HttpServerUtility Server = context. Server;
Context. Response.ContentType = "Text/plain";
Httppostedfile httppostedfile = Request. files["Filedata"];
String Uploadpath = request["folder" + "\";//server. MapPath (request["folder") + "\ \");
if (httppostedfile!= null)
{
Ccnf. Plugin.Upload.Upload Upload = new ccnf. Plugin.Upload.Upload ();
Upload. Savefolder = Uploadpath;
Upload. Picsize = new int[,] {{200, 150}};//generate thumbnails, which size specifications to produce thumbnails, define a two-dimensional array
int result = Upload. SaveAs (Httppostedfile);
if (result = = 1)
{
Context. Response.Write ("1");
}
Else
{
throw new Exception (upload. Error (result));
Context. Response.Write ("0");
}
}
}
public bool IsReusable
{
Get
{
return false;
}
}
}

5. Foreground aspx page call ashx page
Here, I use a third party control, because this is not the focus of my article, so, just briefly say the name of the control is: jquery.uploadify, you can find this JS control code. A JS encapsulation control that is very simple to use.
Through this JS control, the page will upload the file post to the ashx processing file, ASHX will receive data and start uploading.
Postscript
First, the upload function is everywhere, and the main point of this article is to customize the generation of multiple thumbnails. This is very suitable for websites like micro-life Sports Outdoor Mall (http://sports.8t8x.com/), Taobao, etc.
Second, I recalled the design mode again, the temperature of the new, and new discoveries, so, send this article, chat table comfort.
About the author of this article
Ma Zhihuan (Marc), 1981, 2002 Hubei University incomplete, is now dwelling in Guangzhou. 2004 learning Programming, has been 8 years of programming experience, has long been engaged in asp.net b/s aspects of development and design. Strong capability on project solutions, project performance and scalability. You can use mazhiyuan1981@163.com to get in touch with me.
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.