.net 上传图片的2中方式

<script type="text/javascript">
        var i=1
        function addFile()
        {
    
         if (i<8)
            {var str = '<BR> <input type="file" name="File" runat="server" style="width: 300px"/>描述:<input name="text" type="text" style="width: 150px" maxlength="20" />'
            document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
       
            }
        else
            {
                alert("您一次最多只能上传8张图片!")
            }
            i++
        }
function verCode()
{
    alert("验证码输入错误");
}
</script>

<INPUT onclick="addFile()" type="button" value="增加图片(Add)"><br />
                                    <input id="File1" type="file" name="File" runat="server" style="width: 300px"/>
                                    描述:<input  name="text" type="text" style="width: 150px" maxlength="20" />
===========================================================

.cs 代码
 


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Data.SqlClient;
using System.Text;   
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (Session["userid"] != null && Session["user"] != null && Session["model"] != null && Session["userid"].ToString() != "" && Session["user"].ToString() != "" && Session["model"].ToString() != "")
        {
            if (this.ddlAlbum.SelectedValue == "请选择产品的类别")
            {
                Jsp.Alert("请选择类别");
            }
            else
            {
                if (this.txtVerifyCode.Text.Trim().ToUpper() != Session["VerifyCode"].ToString())
                {
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "define", "<script>verCode()</script>");//动态注册脚本
                }
                else
                {

                    lblMessage.Text = "";
                    lblMessage.Visible = false;
                    System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                    System.Text.StringBuilder strmsg = new System.Text.StringBuilder("");
                    string[] rd = Request.Form[1].Split(',');//获得图片描述的文本框字符串数组,为对应的图片的描述
                    string albumid = ddlAlbum.SelectedValue.Trim();
                    int ifile;
                    for (ifile = 0; ifile < files.Count; ifile++)
                    {
                        if (files[ifile].FileName.Length > 0)
                        {
                            System.Web.HttpPostedFile postedfile = files[ifile];

                            string fex = Path.GetExtension(postedfile.FileName);
                            if (fex != ".jpg" && fex != ".JPG" && fex != ".gif" && fex != ".GIF")
                            {
                                strmsg.Append(Path.GetFileName(postedfile.FileName) + "---图片格式不对,只能是jpg或gif<br>");
                                int num2 = ifile + 1;
                                Jsp.Alert("您选择的第" + num2 + "张图片错误!图片格式不正确只能是jpg或gif");
                                imgState = false; break;
                            }
                            if (postedfile.ContentLength > 200 * 1024)//单个文件不能大于200k
                            {
                                strmsg.Append(Path.GetFileName(postedfile.FileName) + "---不能大于1024k<br>");
                                int num1 = ifile + 1;
                                Jsp.Alert("您选择的第" + num1 + "张图片错误!图片大小不能大于200K");
                                imgState = false; break;
                            }

                            System.Drawing.Image image = System.Drawing.Image.FromStream(files[ifile].InputStream);
                            int width = image.Width;
                            int height = image.Height;
                            int num = ifile + 1;
                            if (width > 300 || height > 500)
                            {
                                Jsp.Alert("您选择的第" + num + "张图片错误!您的图片是" + width + "*" + height + "!请您重新上传尺寸小于300*500的图片");
                                imgState = false; break;
                            }
                        }
                    }

                    if (strmsg.Length <= 0)//说明图片大小和格式都没问题
                    {
                        //以下为创建图库目录
                        //string dirname = "pic00" + ddlAlbum.SelectedValue.Trim();

                        string dirpath = Server.MapPath("..//..//dress_corp/ProIMG");
                        //dirpath = dirpath +"\\" + dirname;
                        if (Directory.Exists(dirpath) == false)
                        {
                            Directory.CreateDirectory(dirpath);
                        }
                        Random ro = new Random();
                        int name = 1;
                        if (imgState)
                        {
                            try
                            {
                                for (int i = 0; i < files.Count; i++)
                                {
                                    System.Web.HttpPostedFile myFile = files[i];
                                    string FileName = "";
                                    string FileExtention = "";
                                    string PicPath = "";
                                    FileName = System.IO.Path.GetFileName(myFile.FileName);
                                    string stro = ro.Next(100, 100000000).ToString() + name.ToString();//产生一个随机数用于新命名的图片
                                    string NewName = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + stro;
                                    if (FileName.Length > 0)//有文件才执行上传操作再保存到数据库
                                    {
                                        FileExtention = System.IO.Path.GetExtension(myFile.FileName);

                                        string ppath = dirpath + "\\" + NewName + FileExtention;
                                        myFile.SaveAs(ppath);
                                        string FJname = FileName;
                                        PicPath = NewName + FileExtention;

                                    }
                                    AddPicture(PicPath, rd[i], albumid);//将图片信息保存到数据库
                                }

                                Jsp.GoBack("添加成功", "qy-fab-list.aspx");

                            }
                            catch
                            {
                                Jsp.Alert("添加失败");
                            }
                        }

                    }
                    else
                    {
                        lblMessage.Text = strmsg.ToString();
                        lblMessage.Visible = true;
                    }

                }

            }
        }
        else
        {
            Jsp.GoBack("连接超时,请重新登陆!", "/user/login.aspx");
        }
    }

    public void AddPicture(string imgpath, string imgnote, string albumid)
    {
        StringBuilder strSql = new StringBuilder();
        strSql.Append("insert into e_ProShowPhoto(");
        strSql.Append("PhotoTitle,PhotoFileName,CateType,UserID)");
        strSql.Append(" values (");
        strSql.Append("@PhotoTitle,@PhotoFileName,@CateType,@UserID)");
        SqlParameter[] parameters = {
     new SqlParameter("@PhotoTitle", SqlDbType.VarChar,40),
     new SqlParameter("@PhotoFileName", SqlDbType.VarChar,50),
     new SqlParameter("@CateType", SqlDbType.VarChar,50),
     new SqlParameter("@UserID", SqlDbType.Int,4)
     };
        parameters[0].Value = imgnote;
        parameters[1].Value = imgpath;
        parameters[2].Value = albumid;
        parameters[3].Value = userID;
        SqlHelper.ExecuteSql(strSql.ToString(), parameters);
    }

==============================

<form id="form1" runat="server">

<div>
  图片上传:生成缩略图 加文字水印 图片水印<br />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传图片" /><br />
<asp:Label ID="Label1" runat="server"></asp:Label><br />
 <br />
远程图片抓取(保存到本地)支持jpg、gif、bmp、png<br />
图片抓取后自动以日期+原名称命名<br />
输入远程图片地址(支持Html)<br />
<asp:TextBox ID="TextBox1" runat="server" Height="308px" TextMode="MultiLine" Width="584px"></asp:TextBox>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="开始抓取" /></div>
</form>




using
System.Configuration;
  4using
System.Collections;
  5using
System.Web;
  6using
System.Web.Security;
  7using
System.Web.UI;
  8using
System.Web.UI.WebControls;
  9using
System.Web.UI.WebControls.WebParts;
10using
System.Web.UI.HtmlControls;
11using
System.IO;
12using
System.Net;
13using
System.Text.RegularExpressions;
14

15namespace
ImgUpload
16
{
17   
/// <summary>
18    /// 上传图片生成缩略图及水印 
19    /// </summary>

20    public partial class _Default : System.Web.UI.Page
21   
{
22        protected void Page_Load(object
sender, EventArgs e)
23       
{
24

25        }

26
27        protected void Button1_Click(object
sender, EventArgs e)
28       
{
29            if
(FileUpload1.HasFile)
30           
{
31                string fileContentType =
FileUpload1.PostedFile.ContentType;
32                if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg"
)
33               
{
34                    string name = FileUpload1.PostedFile.FileName;                  // 客户端文件路径

35
36                    FileInfo file = new FileInfo(name);
37                    string fileName = file.Name;                                    // 文件名称

38                    string fileName_s = "x_" + file.Name;                           // 缩略图文件名称
39                    string fileName_sy = "text_" + file.Name;                         // 水印图文件名称(文字)
40                    string fileName_syp = "water_" + file.Name;                       // 水印图文件名称(图片)
41                    string webFilePath = Server.MapPath("ImgUpload/" + fileName);        // 服务器端文件路径
42                    string webFilePath_s = Server.MapPath("ImgUpload/" + fileName_s);  // 服务器端缩略图路径
43                    string webFilePath_sy = Server.MapPath("ImgUpload/" + fileName_sy); // 服务器端带水印图路径(文字)
44                    string webFilePath_syp = Server.MapPath("ImgUpload/" + fileName_syp); // 服务器端带水印图路径(图片)
45                    string webFilePath_sypf = Server.MapPath("aspx.png"); // 服务器端水印图路径(图片)
46
47                    if (!File.Exists(webFilePath))
48                   
{
49                        try

50                        {
51                            FileUpload1.SaveAs(webFilePath);                                // 使用 SaveAs 方法保存文件

52                            AddWater(webFilePath, webFilePath_sy);
53
                            AddWaterPic(webFilePath, webFilePath_syp, webFilePath_sypf);
54                            MakeThumbnail(webFilePath, webFilePath_s, 130, 130, "Cut");     // 生成缩略图方法

55                            Label1.Text = "提示:文件“" + fileName + "”成功上传,并生成“" + fileName_s + "”缩略图,文件类型为:" + FileUpload1.PostedFile.ContentType + ",文件大小为:" + FileUpload1.PostedFile.ContentLength + "B";
56                        }

57                        catch (Exception ex)
58                       
{
59                            Label1.Text = "提示:文件上传失败,失败原因:" +
ex.Message;
60                        }

61                    }

62                    else
63                    {
64                        Label1.Text = "提示:文件已经存在,请重命名后上传"
;
65                    }

66                }

67                else
68                {
69                    Label1.Text = "提示:文件类型不符"
;
70                }

71            }

72        }

73        /**/
74        /// <summary>
75        /// 生成缩略图
76        /// </summary>

77        /// <param name="originalImagePath">源图路径(物理路径)</param>
78        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
79        /// <param name="width">缩略图宽度</param>
80        /// <param name="height">缩略图高度</param>
81        /// <param name="mode">生成缩略图的方式</param>   

82        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
83       
{
84            System.Drawing.Image originalImage =
System.Drawing.Image.FromFile(originalImagePath);
85

86            int towidth =
width;
87            int toheight =
height;
88

89            int x = 0
;
90            int y = 0
;
91            int ow =
originalImage.Width;
92            int oh =
originalImage.Height;
93

94            switch
(mode)
95           
{
96                case "HW"://指定高宽缩放(可能变形)               

97                    break;
98                case "W"://指定宽,高按比例                   

99                    toheight = originalImage.Height * width / originalImage.Width;
100                    break
;
101                case "H"://指定高,宽按比例

102                    towidth = originalImage.Width * height / originalImage.Height;
103                    break
;
104                case "Cut"://指定高宽裁减(不变形)               

105                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
106                   
{
107                        oh =
originalImage.Height;
108                        ow = originalImage.Height * towidth /
toheight;
109                        y = 0
;
110                        x = (originalImage.Width - ow) / 2
;
111                    }

112                    else
113                    {
114                        ow =
originalImage.Width;
115                        oh = originalImage.Width * height /
towidth;
116                        x = 0
;
117                        y = (originalImage.Height - oh) / 2
;
118                    }

119                    break;
120                default
:
121                    break
;
122            }

123
124            //新建一个bmp图片

125            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
126

127            //新建一个画板

128            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
129

130            //设置高质量插值法

131            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
132

133            //设置高质量,低速度呈现平滑程度

134            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
135

136            //清空画布并以透明背景色填充

137            g.Clear(System.Drawing.Color.Transparent);
138

139            //在指定位置并且按指定大小绘制原图片的指定部分

140            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
141                new
System.Drawing.Rectangle(x, y, ow, oh),
142
                System.Drawing.GraphicsUnit.Pixel);
143

144            try

145            {
146                //以jpg格式保存缩略图

147                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
148            }

149            catch (System.Exception e)
150           
{
151                throw
e;
152            }

153            finally
154            {
155
                originalImage.Dispose();
156
                bitmap.Dispose();
157
                g.Dispose();
158            }

159        }

160
161        /**/

162        /// <summary>
163        /// 在图片上增加文字水印
164        /// </summary>

165        /// <param name="Path">原服务器图片路径</param>
166        /// <param name="Path_sy">生成的带文字水印的图片路径</param>

167        protected void AddWater(string Path, string Path_sy)
168       
{
169            string addText = "vs2005.com"
;
170            System.Drawing.Image image =
System.Drawing.Image.FromFile(Path);
171            System.Drawing.Graphics g =
System.Drawing.Graphics.FromImage(image);
172            g.DrawImage(image, 0, 0
, image.Width, image.Height);
173            System.Drawing.Font f = new System.Drawing.Font("Verdana", 60
);
174            System.Drawing.Brush b = new
System.Drawing.SolidBrush(System.Drawing.Color.Green);
175

176            g.DrawString(addText, f, b, 35, 35
);
177
            g.Dispose();
178

179
            image.Save(Path_sy);
180
            image.Dispose();
181        }

182
183        /**/

184        /// <summary>
185        /// 在图片上生成图片水印
186        /// </summary>

187        /// <param name="Path">原服务器图片路径</param>
188        /// <param name="Path_syp">生成的带图片水印的图片路径</param>
189        /// <param name="Path_sypf">水印图片路径</param>

190        protected void AddWaterPic(string Path, string Path_syp, string Path_sypf)
191       
{
192            System.Drawing.Image image =
System.Drawing.Image.FromFile(Path);
193            System.Drawing.Image copyImage =
System.Drawing.Image.FromFile(Path_sypf);
194            System.Drawing.Graphics g =
System.Drawing.Graphics.FromImage(image);
195            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);
196
            g.Dispose();
197

198
            image.Save(Path_syp);
199
            image.Dispose();
200        }

201
202        protected void Button2_Click(object
sender, EventArgs e)
203       
{
204            //自动保存远程图片

205                WebClient client = new WebClient();
206                //备用Reg:<img.*?src=([\"\'])(http:\/\/.+\.(jpg|gif|bmp|bnp))\1.*?>

207                Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase);
208                MatchCollection m =
reg.Matches(TextBox1.Text);
209

210                foreach (Match math in
m)
211               
{
212                    string imgUrl = math.Groups[1
].Value;
213

214                    //在原图片名称前加YYMMDD重名名并上传

215
216                    Regex regName = new Regex(@"\w+.(?:jpg|gif|bmp|png)", RegexOptions.IgnoreCase);
217

218                    string strNewImgName = DateTime.Now.ToShortDateString().Replace("-", "") +
regName.Match(imgUrl).ToString();
219

220                    try

221                    {
222                        //保存图片

223                        client.DownloadFile(imgUrl, Server.MapPath("ImgUpload/Auto/" + strNewImgName));
224

225                    }

226                    catch
227                    {
228                    }

229                    finally
230                    {
231

232                    }

233
234
                client.Dispose();
235            }

236
237            Response.Write("<script>alert('远程图片保存成功,保存路径为ImgUpload/auto')</script>"
);
238

239        }

240    }

241}



=============================================================

前台显示时候
<img src="../Background/tjsp/PiFaImg/<%=IMG%>" width="85" height="85">  

//产品的图片
                if (img != null && img != "")
                {
                    alist1 = DataTransfer.SetMoreInfo(img, ',');
                    for (int i = 0; i < alist1.Length; i++)
                    {
                        bool booState = false;
                        if (infotype == "今日新款")
                        {
                            if (ImgState.GetImgStateBySize("../background/jrxk/PiFaImg/", GetPic(alist[i]), 365, 400))
                            {
                                guangGao = "<img src='/Wholesale%20Member/background/jrxk/PiFaImg/" + GetPic(alist[i]) + "'></img><br>";
                            }
                            else
                            {
                                guangGao = "<img src='/Wholesale%20Member/background/jrxk/PiFaImg/" + GetPic(alist[i]) + "' witch=360 height=400></img><br>";
                            }
                        }
                        if (infotype == "特价商品")
                        {
                            if (ImgState.GetImgStateBySize("../background/tjsp/PiFaImg/", GetPic(alist[i]), 365, 400))
                            {
                                guangGao = "<img src='/Wholesale%20Member/background/tjsp/PiFaImg/" + GetPic(alist[i]) + "'></img><br>";
                            }
                            else
                            {
                                guangGao = "<img src='/Wholesale%20Member/background/tjsp/PiFaImg/" + GetPic(alist[i]) + "' witch=360 height=400></img><br>";
                            }
                        }
                    }


                }
                else
                {
                    if (infotype == "今日新款")
                    {
                        guangGao = "<img src='/Wholesale%20Member/background/jrxk/PiFaImg/no.gif'></img>";
                    }
                    if (infotype == "特价商品")
                    {
                        guangGao = "<img src='/Wholesale%20Member/background/tjsp/PiFaImg/no.gif'></img>";
                    }
                }


=============
    public static  string[] SetMoreInfo(string str,char chr)
    {

      
        if (str == String.Empty || str == null)
            return null;
        else
        {
            string[] alist = str.Split(chr);
            return alist;
        }
    }
============
   /// <summary>
    /// 便利指定路径下的图片
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="picName">图片名</param>
    /// <returns>bool有的话true,没有的话就false</returns>
    public static bool GetImgState(string path,string picName)
    {
        if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(path + picName)))
        {
           
            return true;
        }
        else
        {
            return false;
        }
    }
    /// <summary>
    /// 判断图片是否存在 并且判断是否在指定范围内
    /// </summary>
    /// <param name="path"></param>
    /// <param name="picName"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public static bool GetImgStateBySize(string path, string picName, int width, int height)
    {
        if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(path + picName)))
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(path + picName));
            if (image.Width < width && image.Height < height)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

posted @ 2008-06-16 13:44  林台山人  阅读(904)  评论(0编辑  收藏  举报