如何以当前日期和时间的形式在数据库中保存图像名称

时间:2014-01-28 08:43:03

标签: c# image datetime

我想在名称当前日期和时间的数据库中保存图像。对于Eg。如果要上传名为waterfall.jpg的图像,则应将其保存为20142801020000PM.jpg。 以下是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Globalization;

namespace GalleryAnd_Album
{
    public partial class _Default : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection("Data Source=PRAVIN-LENOVO\\SQLEXPRESS;Initial Catalog=Gallery;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {


        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            if(FU1.HasFile)
            {
                int album_company_id=1;
                string album_addedonstatus="y";
                string album_addedby="0";
                string str=FU1.FileName;

                string a = DateTime.Now.ToString("yyyy-MM-dd HHmmtt") + ".jpg";
                FU1.PostedFile.SaveAs(Server.MapPath(".")+ "//Album//"+a);
                string path = "~//Album//" + a.ToString();
                FU1.SaveAs(path);
                con.Open();
                SqlCommand cmd = new SqlCommand("Insert into Album values ('" + txttitle.Text + "','" + txtdescription.Text + "','" + path + "','" + album_company_id + "','" + album_addedby + "','" + album_addedonstatus + "')", con);
                cmd.ExecuteNonQuery();

                lblmessage.Text="Image uploaded succesfully";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;

                con.Close();               
            }
        }      

        protected void lbview_Click(object sender, EventArgs e)
        {
            Response.Redirect("view_album.aspx");
        }

    }
}

我的错误是:

SaveAs方法配置为需要有根路径,路径'〜// Album // 2014-01-28 1406PM.jpg'未植根。

2 个答案:

答案 0 :(得分:2)

调用SaveAs时需要提供绝对文件路径:

FU1.SaveAs(Server.MapPath(path));

答案 1 :(得分:0)

您的问题的第一部分可以通过

解决
a = DateTime.Now.ToString("yyyy-MM-dd HHmmtt") + ".jpg";
string rootedPath = Server.MapPath("~//Album//" + a.ToString());
FU1.PostedFile.SaveAs(rootedPath);

并删除第二个(冗余的)SaveAs

但是你应该注意你的sql命令字符串。对Sql Injection来说,这是一个很大的安全风险

con.Open();
string cmdText = "Insert into Album values (@title, @desc, @path, @aid, @aby, @stat";
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.Parameters.AddWithValue("@title",txttitle.Text );
cmd.Parameters.AddWithValue("@desc",txtdescription.Text );
cmd.Parameters.AddWithValue("@path", rootedPath);
cmd.Parameters.AddWithValue("@aid",album_company_id);
cmd.Parameters.AddWithValue("@aby",album_addedby );
cmd.Parameters.AddWithValue("@stat",album_addedonstatus );
cmd.ExecuteNonQuery();