1

我正在做一个用户配置文件,首先用户选择图片并使用此代码上传到一个文件夹中,上传后显示图像:

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 个,名词字段是数据库上唯一不能为空的字段

后面的代码:

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 上的内容)时,图像 url 将保存到字段 Imagen 上的数据库中,该字段是 varchar 50,但不工作,我得到:无法将值 NULL 插入到列 'Nombre'、表 'prueba.dbo.Curriculum' 中;列不允许空值。插入失败。该语句已终止。

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

知道如何将图像 url 保存到数据库中吗?希望我的解释清楚!

谢谢!:D

4

1 回答 1

0

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

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

string strQuery = "UPDATE curriculum SET imagen = @imgPicture WHERE Nombre = ???";
于 2012-07-11T03:20:49.553 回答