您的位置:首页 > 其它

加载上传图片,获取文件名、文件路径并保存到程序的文件夹中

2015-09-05 11:51 791 查看
using  System.Data;

using System.Data.SqlClient;

using configuration;

using System.IO;

//将数据添加到数据库,然后将照片传到相应文件夹中

//在项目中新建文件夹用于存放加载的图片  MyFile

static string connStr=ConfigurationManager.AppSettings("ConnStr");

SqlConnection conn=new SqlConnection(connStr);

protected  viod Page_Load(object sender ,EventArgs e)

{

   BindPhoto();

}

void BindPhoto()

{

    string sql ="select * from PhotoInfo";

    SqlDataAdapter da=new SqlDataAdapter(sql,conn);

    DataSet ds=new DataSet();

     da.Fill(ds); // 填充到ds

     GridView1.DataSource=ds.Table[0];

     GridView1.DataBind();

}

protection void Button_Click(Object sender ,EventArgs  e)

{

   //获取文件名称

   string myFileName= FileUpload1.FileName;

  //获取文件夹路径

   string myFullFileName=FileUpload1.PostedFile.FileName;

   //获取路径的后缀并转换成小写

    string mySuffix=Path.GetExtention(myFullFileName).ToLower();

   //判断后缀名是否是图片格式

    if(mySuffix==".jpg"||mySuffix==".gif"||mySuffix==".bmp"||mySuffix==".jpeg")

    {

      

         //获取图片大小

          int imgLength=FileUpload1.PostedFile.ContentLength;

          if((imgLength/1024)<1024)

          {   

                  //添加到数据库

                   string sql="insert into PhotoInfo(PhotoTitle,PhotoName,PhotoDes)values(' "+txtTitle.Text+"  ', ' "+myFileName +" ', ' "+txtDes.Text+" ');

                   SqlCommand  cmd=new SqlCommand(sql,conn);

                    conn.Open();

                     int i=cmd.ExecuteNonQuery();

                      conn.Close();

                     if(i>0)

                      {

                        string upload=Server.GetMap("MyFile\\"+myFileName); // 获取要上传到的文件夹相对路径

                         FileUpload1.SaveAs(upload); //保存

                        Response.Write("上传成功") ;

                      }

                  else

                  {

                         Response.Write("图片上传未成功") ;

                   }

           }

            else

             {

                   Response.Write("上传图片太大");

               }

       }

        else

          {

                Response.Write("图片格式不符");

             }

}

//修改web.config  上传图片大小等 ,在web.config中添加httpRuntime元素,如下

<configuration>

        <system.web>

                 <httpRuntime maxRequestLength=8192

                   useFullQualifiedRedirectUrl=true

                   executionTimeout=45

                    versionHeader=.1.2.4128/>

          </system.web>

</configuration>

//在winform中获取相对路径和在web中

 string dir=Direction.GetCurrentDirection;

string dir=Server.GetMap("文件名称");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: