我知道用Upload控件上传图片到某一文件夹。 但应该怎么实现在上传时按一定的规则重命名图片,并把图片在服务器上的地址写入数据库?如果能给一段演示C#代码(结合Upload控件)更是不胜感激。谢谢。

解决方案 »

  1.   

    //上传
            String path = Server.MapPath("~/UpFile/");// +DateTime.Now.ToShortDateString();
            if (!Directory.Exists(path))
            {
                //在Upload目录下创建了一个文件夹    
            Directory.CreateDirectory(path);
            }        String filepath = this.FileUpload1.PostedFile.FileName;
            String myextend = System.IO.Path.GetExtension(filepath);
            Maticsoft.Model.TB_News Tad = new Maticsoft.Model.TB_News();
            Random ran = new Random(DateTime.Now.Millisecond);
            //生成随机的文件名
            String newfilename = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(9999) + myextend;
            String newfilename1 = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(9999) +"shuiyin"+ myextend;
            //判断文件是否存在
            if (filepath.ToString() != "")
            {            sting n_Image = "UpFile/" + newfilename1;
                           if (!String.IsNullOrEmpty(filepath))
                {
                    //判断文件大小
                    int length = int.Parse(ConfigurationManager.AppSettings["length"]);
                    if (this.FileUpload1.PostedFile.ContentLength > length)
                    {
                        Response.Write("<script>alert('文件大小超出" + length / 1024 + "k,不允许上传');history.back();</script>");
                        Response.End();
                    }
                    else
                    {
                        //判断文件类型
                        String[] extend = ConfigurationManager.AppSettings["extend"].Split('|');
                        //上传的文件类型
                        String myextend1 = System.IO.Path.GetExtension(filepath);
                        bool flag = true;
                        foreach (String var in extend)
                        {
                            if (var == myextend1)
                            {
                                flag = false;
                                break;
                            }
                        }                    if (flag)//为真不允许的文件类型
                        {
                            Response.Write("<script>alert('文件文件类型不匹配,只允许的类型有" + String.Join("|", extend) + "');history.back();</script>");
                            Response.End();                    }                    //保存文件
                      this.FileUpload1.PostedFile.SaveAs(path + "\\" + newfilename);
                                 }
      

  2.   


        public String Up_Img()
        {
            string path = string.Empty;
            string fullfilename = this.FileUpload1.PostedFile.FileName;
            if (fullfilename.Length > 2)
            {
                string type1 = fullfilename.Substring(fullfilename.LastIndexOf("."));
                string dt = DateTime.Now.ToString().Trim().Replace("-", "").Replace(":", "").Replace(" ", "");
                string filename = dt.ToString() + type1.ToString();
                string lujing = Server.MapPath("..\\") + "..\\Upload\\Images\\" + filename;
                FileUpload1.PostedFile.SaveAs(lujing);
                path = "Upload\\Images\\" + filename;
            }
            else
            {
                path = "Upload\\Images\\nopic.bmp"; //没有选择图片的情况下录入的图片地址。
            }
            return path;
        }
    插入数据库很简单的吧。上面的方法是返回个路径,insert进去就行了。
      

  3.   

    为了防止保存到数据库中的图片名称重复
    通常会这样做:
    获取当前时间的毫秒数   再接上一个随机数 做为图片的名称
    下面是主要代码
    //生成唯一标识的文件名
    string fileName = DateTime.Now.Ticks.ToString() + new Random().Next();
    //获取扩展名   例如  .jpg
    string format = this.FileUpload_Image.FileName.Substring(this.FileUpload_Image.FileName.LastIndexOf('.'));
    //得到图片名称
    string name=fileName+format;
    //将图片保存到uploads文件夹下           上传图片
    this.FileUpload_Image.SaveAs(Server.MapPath("uploads/" + name));  //uploads事先创建好接下来只需把图片名称保存到数据库就可以了
      

  4.   

    哦对了我上面的那个方法,如果你一个界面上有好几个图片来同时上传的话,最好能用线程sleep个几十毫秒,要不可能会因为速度太快而少上传图片。不过如果只有一张的话还是没有事情的。
      

  5.   

    Random rand = new Random();
    string num = rand.Next(100, 1000).ToString();
    string name = DateTime.Now.ToFileTime().ToString();string filename = url +name
    是不是这样的啊 
      

  6.   


    能给一段代码演示下线程sleep的用法吗?谢谢
      

  7.   

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">        <asp:FileUpload ID="FileUpload1" runat="server"  />
        
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="上传" />  
      
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:extentionConnectionString %>" 
            InsertCommand="INSERT INTO [TB_img] ([img]) VALUES (@img)" >
            
          <InsertParameters>
          <asp:Parameter Name="img" Type="String"/>
          </InsertParameters>
        </asp:SqlDataSource>
        </form>
    </body>
    </html>
      

  8.   

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    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.Xml.Linq;
    using System.IO;public partial class Default3 : System.Web.UI.Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
             string myPath = imgPath();
             if (!(myPath == ""))
             {
                 try
                 {
                     SqlDataSource1.InsertParameters["img"].DefaultValue = myPath;
                     SqlDataSource1.Insert();             }             catch
                 {
                     Response.Write("上传失败,请重试。");
                 }
             }
            
        }    public String imgPath()
        {
            string name = this.FileUpload1.PostedFile.FileName;
            Random ran = new Random(DateTime.Now.Millisecond);
            string path = string.Empty;        if (this.FileUpload1.HasFile)
            {
                if (this.FileUpload1.FileBytes.Count() < 1024000)
                {                //string type = name.Substring(name.LastIndexOf(".")).ToLower(); 学习了一下三楼获得扩展名的方法,很好用
                    string type = System.IO.Path.GetExtension(name).ToLower();
                    string[] allowedType = { ".gif", ".jpg", ".bmp", ".png" };
                    bool checkTpye=false;
                    for (int i = 0; i < allowedType.Length; i++)
                    {
                        if(allowedType[i] == type)
                        {
                           checkTpye=true;
                        }
                       
                    }                    if (checkTpye)
                        {
                            try
                            {
                                string dt = DateTime.Now.ToString("yyyyMMddhhmmss").Trim();
                                string newName = dt + ran.Next(9999) + type;
                                path = "Upload\\Images\\" + newName;
                                string pathRoot = Server.MapPath("~/Upload/Images/");                            if (!Directory.Exists(pathRoot))
                                {
                                    Directory.CreateDirectory(pathRoot);
                                }                            this.FileUpload1.PostedFile.SaveAs(pathRoot + newName);
                                Response.Write("上传成功");
                            }                        catch
                            {
                                Response.Write("上传失败,请重试。");
                            }
                        }
                        else
                        {
                            Response.Write("不是允许的文件类型");
                        }
                    
                }
                else
                {
                    Response.Write("超过大小限制");
                }        }        else
            {
                path = "Upload\\Images\\noPic.jpg";
                Response.Write("你没有上传图片,系统将使用默认图片");
            }        return path;
        }   
         
        }
      

  9.   

    如果要配置全局的上传文件大小,可在web.config里
    <system.web>
            <httpRuntime maxRequestLength="250000"/>
    </system.web>
      

  10.   

    5 楼 jianlanzq,如果你一个界面上有好几个图片来同时上传的话,怎么用线程sleep个几十毫秒,希望能给个演示,谢谢
      

  11.   

    用sleep太影响效率了,你看以下代码,如果一次上传的图多,人为使其延迟的时间都会很久,还要加上上传时间,用户会以为死机了using System.Threading;public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {    }
        protected void Button1_Click(object sender, EventArgs e)
        {
            string dt =DateTime.Now.ToString()+":"+ DateTime.Now.Millisecond.ToString();
           
            Response.Write(dt);
            Thread.Sleep(10000);
           dt = DateTime.Now.ToString() + ":" + DateTime.Now.Millisecond.ToString();        Response.Write("<br/>"+dt);
        }
    }
      

  12.   

    用sleep太影响效率了,你看以下代码,如果一次上传的图多,人为使其延迟的时间都会很久,还要加上上传时间,用户会以为死机了using System.Threading;public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {    }
        protected void Button1_Click(object sender, EventArgs e)
        {
            string dt =DateTime.Now.ToString()+":"+ DateTime.Now.Millisecond.ToString();
           
            Response.Write(dt);
            Thread.Sleep(10000);
           dt = DateTime.Now.ToString() + ":" + DateTime.Now.Millisecond.ToString();        Response.Write("<br/>"+dt);
        }
    }
      

  13.   

    最好用if (filepath.ToString() != "") 断定文件是否存在,然后重新随机命名。