图像路径进入sql数据库

时间:2012-07-11 03:16:11

标签: c# asp.net sql

我正在做一个用户个人资料,首先用户选择图片并上传到带有此代码的文件夹中,图片会在上传后显示:

protected void btnUpload_Click(object sender, EventArgs e)
{
    // Initialize variables
    string sSavePath;
    string sThumbExtension;
    int intThumbWidth;
    int intThumbHeight;

    // Set constant values
    sSavePath = "images/";
    sThumbExtension = "_thumb";
    intThumbWidth = 160;
    intThumbHeight = 120;

    // If file field isn’t empty
    if (filUpload.PostedFile != null)
    {
        // Check file size (mustn’t be 0)
        HttpPostedFile myFile = filUpload.PostedFile;
        int nFileLen = myFile.ContentLength;
        if (nFileLen == 0)
        {
            lblOutput.Text = "El archivo no fue cargado.";
            return;
        }

        // Check file extension (must be JPG)
        if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
        {
            lblOutput.Text = "El archivo debe tener una extensión JPG";
            return;
        }

        // Read file into a data stream
        byte[] myData = new Byte[nFileLen];
        myFile.InputStream.Read(myData, 0, nFileLen);

        // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an 
        // incremental numeric until it is unique
        string sFilename = System.IO.Path.GetFileName(myFile.FileName);
        int file_append = 0;
        while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
        {
            file_append++;
            sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                             + file_append.ToString() + ".jpg";
        }

        // Save the stream to disk
        System.IO.FileStream newFile
                = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
                                           System.IO.FileMode.Create);
        newFile.Write(myData, 0, myData.Length);
        newFile.Close();

        // Check whether the file is really a JPEG by opening it
        System.Drawing.Image.GetThumbnailImageAbort myCallBack =
                       new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
        Bitmap myBitmap;
        try
        {
            myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));

            // If jpg file is a jpeg, create a thumbnail filename that is unique.
            file_append = 0;
            string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                                     + sThumbExtension + ".jpg";
            while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
            {
                file_append++;
                sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
                               file_append.ToString() + sThumbExtension + ".jpg";
            }

            // Save thumbnail and output it onto the webpage
            System.Drawing.Image myThumbnail
                    = myBitmap.GetThumbnailImage(intThumbWidth,
                                                 intThumbHeight, myCallBack, IntPtr.Zero);
            myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
            imgPicture.ImageUrl = sSavePath + sThumbFile;


            // Displaying success information
            lblOutput.Text = "El archivo fue cargado con exito!";

            // Destroy objects
            myThumbnail.Dispose();
            myBitmap.Dispose();
        }
        catch (ArgumentException errArgument)
        {
            // The file wasn't a valid jpg file
            lblOutput.Text = "No es un archivo .jpg valido";
            System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
        }
    }
}

之后,用户完成配置文件的其他字段(名称,电子邮件等),有一个保存按钮,并使用以下内容保存到数据库中:

这是前面的代码

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pruebaConnectionString %>"
    InsertCommand="INSERT INTO Curriculum(Nombre, Correo) VALUES (@TextBox1, @TextBox2)">
    <InsertParameters>
        <asp:ControlParameter ControlID="TextBox1" DefaultValue="" Name="TextBox1" PropertyName="Text" />
        <asp:ControlParameter ControlID="TextBox2" DefaultValue="" Name="TextBox2" PropertyName="Text" />                     
    </InsertParameters>
</asp:SqlDataSource>

实际上还有更多的字段,但为了简化它我只是复制前2个,nombre字段是数据库中唯一不能为空的字段

代码背后:

protected void Button1_Click(object sender, EventArgs e)
{
                SqlDataSource1.Insert();

        String strConn = "Data Source=TOSHI;Initial Catalog=prueba;Integrated Security=True";
        SqlConnection conn = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        string strQuery = "Insert into curriculum (imagen) values (@imgPicture)";
        cmd.CommandText = strQuery;
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@imgPicture", (imgPicture.ImageUrl == null ? (object)DBNull.Value : (object)imgPicture.ImageUrl));
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
}

现在我要做的是当用户点击保存按钮(或方法button1_click上的内容)时,图像网址将保存到数据库中的字段Imagen上,这是一个varchar 50,但是不工作,我得到:不能将值NULL插入列'Nombre',表'prueba.dbo.Curriculum';列不允许空值。 INSERT失败。 该语句已终止。

但是如果我只使用SqlDataSource1.Insert()离开button1_click方法;这些字段会保存到数据库中。

知道如何将图片网址保存到数据库中吗?希望我明白我的解释!

谢谢! :d

1 个答案:

答案 0 :(得分:0)

您是在尝试创建新记录(您需要指定所有值)还是要更新记录?

目前您的代码正在尝试执行INSERT,这将在课程表中创建新记录,但您只设置1值。也许你想做一个UPDATE呢?

string strQuery = "UPDATE curriculum SET imagen = @imgPicture WHERE Nombre = ???";