c#多图片上传
用到的一个弹出窗口类(namespace:PublicClassLibrary):
MessageBox.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Web;
5
6 namespace PublicClassLibrary
7 {
8 /// <summary>
9 /// 用在Web中的 服务端 生成js 在web客户的弹出窗口
10 /// </summary>
11 public class MessageBox
12 {
13
14 /// <summary>
15 /// 显示消息提示对话框
16 /// </summary>
17 /// <param name="page">当前页面指针,一般为this</param>
18 /// <param name="msg">提示信息</param>
19 public static void Show(System.Web.UI.Page page, string msg)
20 {
21 // page.RegisterStartupScript("message", "<script language='javascript' defer>alert('" + msg.ToString() + "');</script>");
22 page.ClientScript.RegisterStartupScript(page.GetType(), null, "<script language='javascript' defer>alert('" + msg.ToString() + "');</script>");
23 }
24 /// <summary>
25 /// 控件点击 消息确认提示框
26 /// </summary>
27 /// <param name="Control">当前控件,如this.textbox</param>
28 /// <param name="msg"></param>
29 public static void ShowConfirm(System.Web.UI.WebControls.WebControl Control, string msg)
30 {
31 //Control.Attributes.Add("onClick","if (!window.confirm('"+msg+"')){return false;}");
32 Control.Attributes.Add("onclick", "return confirm('" + msg + "');");
33 }
34 /// <summary>
35 /// 刷新页面
36 /// </summary>
37 /// <param name="page"></param>
38 public static void Refresh(System.Web.UI.Page page)
39 {
40 StringBuilder Builder = new StringBuilder();
41 Builder.Append("<script language='javascript' defer>");
42 Builder.Append("location.href=location.href");
43 Builder.Append("</script>");
44 page.ClientScript.RegisterStartupScript(page.GetType(), null, Builder.ToString());
45
46 }
47 /// <summary>
48 /// 显示消息提示框,并刷新页面
49 /// </summary>
50 /// <param name="page"></param>
51 /// <param name="msg"></param>
52 public static void ShowAndRefresh(System.Web.UI.Page page,string msg)
53 {
54 StringBuilder Builder = new StringBuilder();
55 Builder.Append("<script language='javascript' defer>");
56 Builder.AppendFormat("alert('{0}');", msg);
57 Builder.Append("location.href=location.href;");
58 Builder.Append("</script>");
59 //page.RegisterStartupScript("message", Builder.ToString());
60 page.ClientScript.RegisterStartupScript(page.GetType(), null, Builder.ToString());
61
62 }
63 /// <summary>
64 /// 显示消息提示对话框,并进行页面跳转
65 /// </summary>
66 /// <param name="page">当前页面指针,一般为this</param>
67 /// <param name="msg">提示信息</param>
68 /// <param name="url">跳转的目标URL</param>
69 ///
70 public static void ShowAndRedirect(System.Web.UI.Page page, string msg, string url)
71 {
72 StringBuilder Builder = new StringBuilder();
73 Builder.Append("<script language='javascript' defer>");
74 Builder.AppendFormat("alert('{0}');", msg);
75 Builder.AppendFormat("location.href='{0}'", url);
76 Builder.Append("</script>");
77 //page.RegisterStartupScript("message", Builder.ToString());
78 page.ClientScript.RegisterStartupScript(page.GetType(), null, Builder.ToString());
79
80 }
81
82 /// <summary>
83 /// 显示消息提示对话框,确定时将进行页面跳转,并进行页面跳转
84 /// </summary>
85 /// <param name="page">当前页面指针,一般为this</param>
86 /// <param name="msg">提示信息</param>
87 /// <param name="url">跳转的目标URL</param>
88
89 public static void ShowConfirmAndRedirect(System.Web.UI.Page page, string msg, string url)
90 {
91 StringBuilder Builder = new StringBuilder();
92 Builder.Append("<script language='javascript' defer>");
93 Builder.AppendFormat("if (confirm('{0}')==true)", msg);
94 Builder.AppendFormat("top.location.href='{0}'", url);
95 Builder.Append("</script>");
96 //page.RegisterStartupScript("message", Builder.ToString());
97 page.ClientScript.RegisterStartupScript(page.GetType(), null, Builder.ToString());
98
99 }
100 /// <summary>
101 /// 输出自定义脚本信息
102 /// </summary>
103 /// <param name="page">当前页面指针,一般为this</param>
104 /// <param name="script">输出脚本</param>
105 public static void ResponseScript(System.Web.UI.Page page, string script)
106 {
107 // page.RegisterStartupScript("message", "<script language='javascript' defer>" + script + "</script>");
108 page.ClientScript.RegisterStartupScript(page.GetType(), null, "<script language='javascript' defer>alert('" + script.ToString() + "');</script>");
109 }
110 /// <summary>
111 /// 输出自定义脚本信息
112 /// </summary>
113 /// <param name="page">当前页面指针,一般为this</param>
114 /// <param name="script">输出脚本</param>
115 public static void ResponseScript(string script)
116 {
117 System.Web.HttpContext.Current.Response.Write("<script language='javascript' defer>" + script + "</script>");
118 }
119 /// <summary>
120 /// 获得焦点
121 /// </summary>
122 /// <param name="ctrl">控件名(this.TextBox)</param>
123 /// <param name="page">this.page</param>
124 public static void SetFocus(System.Web.UI.Control ctrl, System.Web.UI.Page page)
125 {
126 string Script = "<SCRIPT language='javascript' defer>document.getElementById('" + ctrl.ID + "').focus() </SCRIPT>";
127 // page.RegisterStartupScript("focus", s);
128 page.ClientScript.RegisterStartupScript(page.GetType(), null, Script);
129 }
130 }
131 }
上传的前台页面WebForm1:可以上传一张缩略图和多张图片。
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <html xmlns="http://www.w3.org/1999/xhtml">
6 <head runat="server">
7 <title></title>
8 <script src="jquery-1.4.min.js" type="text/javascript"></script>
9 <script src="jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
10 <script type = "text/javascript">
11 //由于不同浏览器,使用的js方法不一样,所有要分别判断一下
12 //js下的table.insertRow ie and firefox的区别:http://www.cnblogs.com/zhouxiuquan/archive/2011/12/28/2305169.html
13 //IE和Firefox下event乱谈:http://www.cnblogs.com/zhouxiuquan/archive/2011/12/28/2305165.html
14 //增加一行
15 //<![CDATA[
16 // $(document).ready(function () {
17 function addRow(eventTag) {
18 var event = eventTag || window.event;
19 if ($.browser.mozilla || navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
20 var oRow = event.target.parentNode.parentNode;
21 var oTable = oRow.parentNode;
22 oNewRow = oTable.insertRow(-1);
23 for (i = 0; i < oRow.cells.length; i++) {
24 oNewRow.insertCell(-1).innerHTML = oRow.cells[i].innerHTML;
25 $("#delbtn").removeAttr("disabled");
26 }
27 }
28 else {
29 var oRow = event.srcElement.parentNode.parentNode;
30 var oTable = oRow.parentNode;
31 oNewRow = oTable.insertRow();
32 for (i = 0; i < oRow.cells.length; i++) {
33 oNewRow.insertCell().innerHTML = oRow.cells[i].innerHTML;
34 }
35 oRow.all("delbtn").disabled = false;
36 oNewRow.all("delbtn").disabled = false;
37 }
38 }
39
40
41 function delRow(eventTag) {
42 var event = eventTag || window.event;
43 if ($.browser.mozilla || navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
44 var oRow = event.target.parentNode.parentNode;
45 var oTable = oRow.parentNode.parentNode;
46 if (oTable.rows.length > 1) {
47 oTable.deleteRow(oRow.rowIndex);
48 if (oTable.rows.length == 1) {
49 $("#delbtn").attr("disabled","disabled");
50 }
51 }
52 }
53 else {
54 var oRow = event.srcElement.parentNode.parentNode;
55 var oTable = oRow.parentNode.parentNode;
56 if (oTable.rows.length > 1) {
57 oTable.deleteRow(oRow.rowIndex);
58 if (oTable.rows.length == 1) {
59 oTable.all("DelBtn").disabled = true;
60 }
61 }
62 }
63 }
64 //]]>
65 </script>
66 </head>
67 <body>
68 <form id="form1" runat="server">
69 <div>
70 <table>
71 <tr>
72 <td>缩略图:</td>
73 <td><asp:FileUpload ID = "FileUpload1" runat = "server" /></td>
74 </tr>
75 <tr>
76 <td>图片:</td>
77 <td>
78 <table>
79 <tr>
80 <td><input type = "file" name = "filepath" id = "filepath"/></td>
81 <td><input type = "button" id = "addbtn" name = "addbtn" value = "添加" onclick="addRow(event)" />
82 <input type = "button" id = "delbtn" name = "delbtn" value = "删除" onclick = "delRow(event)" disabled = "disabled"/>
83 </td>
84 </tr>
85 </table>
86 </td>
87 </tr>
88 <tr>
89 <td colspan = "2"><asp:Button ID = "Save" OnClick = "saveBtn_Click" Text = "保存" runat = "server" /></td>
90
91 </tr>
92 </table>
93
94 </div>
95 <div>
96 <asp:Repeater ID = "Show" runat = "server" >
97 <ItemTemplate>
98 <asp:Image ID = "imageshow" ImageUrl = "<%#(string)Container.DataItem%>" runat = "server" />
99 </ItemTemplate>
100 </asp:Repeater>
101 </div>
102 </form>
103 </body>
104 </html>
后台代码:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7 using System.IO;
8 //包含弹出窗口的messagebox类。
9 using PublicClassLibrary;
10
11 namespace WebApplication1
12 {
13 public partial class WebForm1 : System.Web.UI.Page
14 {
15 //imagepath 用于存放上传的多张图片的相对路径,用于长传之后能立即在下边显示
16 List<string> imagepath = new List<string>();
17 protected void Page_Load(object sender, EventArgs e)
18 {
19 if (HttpContext.Current.Session["imgpath"] != null)
20 {
21
22 imagepath = (List<string>)HttpContext.Current.Session["imgpath"];
23 }
24
25 }
26 void Page_PreRender()
27 {
28
29
30 Show.DataSource = imagepath;
31 Show.DataBind();
32 }
33 protected bool Check(string strName)
34 {
35 //返回文件的小写后缀名
36 string afterName = Path.GetExtension(strName).ToLower();
37 switch (afterName)
38 {
39 case ".jpg":
40 return true;
41 case ".jpeg":
42 return true;
43 case ".gif":
44 return true;
45 case ".png":
46 return true;
47 case ".bmp":
48 return true;
49 default:
50 return false;
51 }
52
53 }
54 #region 上传文件
55 /// <summary>
56 /// 上传缩略图并创建文件夹。UploadFile/yyyyMMdd/Guid
57 /// </summary>
58 /// <param name="guid">图片新闻编号,用于创建文件夹</param>
59 /// <param name="guidName">缩略图名称,用于修改缩略图的名称</param>
60 public void UploadNewsPicture(string guid, string guidName)
61 {
62 //图片压缩
63 ImageRehandLingClass image = new ImageRehandLingClass();
64 //上传文件
65 if (FileUpload1.HasFile)
66 {
67 try
68 {
69 //获取后缀名
70 string fileExt = Path.GetExtension(FileUpload1.FileName).ToLower();
71 //var path1 = Server.MapPath("/Upload/Thumbnail/"); //存放缩略图
72 string path2 = Server.MapPath("/Upload/Thumbnail/"); //存放原图
73 //检查当前年月日的文件夹是否存在不存在创建
74 //if (!Directory.Exists(path2 + DateTime.Now.ToString("yyyyMMdd")))
75 // Directory.CreateDirectory(path2 + DateTime.Now.ToString("yyyyMMdd"));
76 //检查当前guid的文件夹是否存在如果存在创建
77 if (!Directory.Exists(path2 + DateTime.Now.ToString("yyyyMMdd") + "/" + guid))
78 Directory.CreateDirectory(path2 + DateTime.Now.ToString("yyyyMMdd") + "/" + guid);
79 //先判断文件大小再判断文件格式
80 //4M=4*1024*1024=4194304 B(字节)
81 if (FileUpload1.FileContent.Length < 4194304) {
82 if (Check(FileUpload1.FileName))
83 {
84 //获取物理路径
85 var path = Server.MapPath("/Upload/Thumbnail/" + DateTime.Now.ToString("yyyyMMdd") + "/" + guid + "/");
86 //上传文件
87 FileUpload1.SaveAs(path + FileUpload1.FileName);
88 //压缩缩略图 ,将原图和缩略图放在一个文件夹中,不加水印
89 image.MakeThumbnail(path + FileUpload1.FileName, path + guidName + fileExt, 300, 200, true, 80, false, "", ImageRehandLingClass.MarkPosition.MP_Left_Bottom);
90 //用于存放图片的相对路径
91 string imageurl1 = "/Upload/Thumbnail/" + DateTime.Now.ToString("yyyyMMdd") + "/" + guid + "/" + guidName + fileExt;
92 imagepath.Add(imageurl1);
93 }
94 else
95 {
96 MessageBox.Show(Page, "缩略图上传格式不正确!请上传jpg、jpeg、gif、png、bmp格式的文件");
97 }
98 }
99 else {
100 MessageBox.Show(this, "缩略图上传的文件不能大于4M,请压缩后试试!");
101 }
102
103 }
104 catch (Exception ex)
105 {
106 throw ex;
107 }
108 }
109 }
110
111 /// <summary>
112 /// 上传多个图片
113 /// </summary>
114 public void UploadFile(string guid)
115 {
116 //图片压缩
117 ImageRehandLingClass image = new ImageRehandLingClass();
118 //获得页面上所有的上传控件
119 HttpFileCollection files = HttpContext.Current.Request.Files;
120
121 string path2 = Server.MapPath("/Upload/Picture/");
122 //检查当前年月日的文件夹是否存在不存在创建
123 //if (!Directory.Exists(path2 + DateTime.Now.ToString("yyyyMMdd")))
124 // Directory.CreateDirectory(path2 + DateTime.Now.ToString("yyyyMMdd"));
125 //检查当前guid的文件夹是否存在如果存在创建
126 if (!Directory.Exists(path2 + DateTime.Now.ToString("yyyyMMdd") + "/" + guid))
127 Directory.CreateDirectory(path2 + DateTime.Now.ToString("yyyyMMdd") + "/" + guid);
128
129 try
130 {
131 //从1开始,就去掉了单独上传的缩略图
132 for (int i = 1; i < files.Count; i++)
133 {
134 //图片名称guid
135 //var guidName = Guid.NewGuid();
136 //缩略图GUID
137 var guidImageName = Guid.NewGuid();
138
139 HttpPostedFile postedFile = files[i];
140 //得到用户选择的文件名
141 string fileName = Path.GetFileName(postedFile.FileName);
142 //获取后缀名
143 string fileExt = Path.GetExtension(postedFile.FileName).ToLower();
144
145 //判断如果得到的文件名不为空的话对它进行以下操作
146 if (fileName != "")
147 {
148 if (files[i].ContentLength < 4194304)
149 {
150 if (Check(postedFile.FileName))
151 {
152 //获取物理路径
153 var path = Server.MapPath("/Upload/Picture/" + DateTime.Now.ToString("yyyyMMdd") + "/" + guid + "/");
154 //上传文件
155 postedFile.SaveAs(path + fileName);
156 //压缩缩略图
157 image.MakeThumbnail(path + fileName, path + guidImageName + fileExt, 300, 200, true, 80, false, "", ImageRehandLingClass.MarkPosition.MP_Left_Bottom);
158 //imageurl 存放图片的相对路径,用于显示图片
159 string imageurl1 = "/Upload/Picture/" + DateTime.Now.ToString("yyyyMMdd") + "/" + guid + "/" + guidImageName + fileExt;
160 imagepath.Add(imageurl1);
161 }
162 else
163 {
164 MessageBox.Show(Page, "图片上传格式不正确!请上传jpg、jpeg、gif、png、bmp格式的文件");
165 }
166 }else{
167 MessageBox.Show(Page, "图片上传的文件不能大于4M,请压缩后试试!");
168
169 }
170
171 }
172 }
173 }
174 catch (Exception ex)
175 {
176 throw ex;
177 }
178 }
179 #endregion
180
181 //保存
182 protected void saveBtn_Click(object sender, EventArgs e)
183 {
184 try
185 {
186 //生成guid记录当前保存的一组图片的ID。
187 string guid1 = Guid.NewGuid().ToString();
188 //生成单独上传的一张缩略图的guid;
189 string guidname1 = Guid.NewGuid().ToString();
190 UploadNewsPicture(guid1, guidname1);
191 UploadFile(guid1);
192 HttpContext.Current.Session["imgpath"] = imagepath;
193 }
194 catch (Exception ex)
195 {
196 this.Response.Write(ex);
197 }
198
199 }
200 }
201 }
多文件上传时,最好能在前台页面上进行判断文件的大小、类型,哪位大师可以写一下,不胜感激。
再者判断文件类型通过后缀名判断只是一种初级的判断方式,是不是可以通过判断文件的MIME类型。我搜索的有人用这样一个方法:
1 public Boolean IsImage(string path)
2 {
3 try
4 {
5 System.Drawing.Image img = System.Drawing.Image.FromFile(path);
6 return true;
7 }
8 catch (Exception e)
9 {
10 return false;
11 }
12 }
不知道是否可行,有时间验证一下
链接:http://wenwen.soso.com/z/q274056734.htm
http://www.cnblogs.com/sunfny/archive/2011/01/14/1935360.html