【问题标题】:unable to update profile picture using varbinary无法使用 varbinary 更新个人资料图片
【发布时间】:2013-06-03 08:29:19
【问题描述】:

我正在尝试使用 varbinary (SQL Server 2008) 更新我的个人资料图片。它似乎没有更新我放在文件上传中的图片。下面是我用来更新我的个人资料图片的代码。请帮我看看我的代码的哪一部分做错了。 谢谢。

protected void btnUpload_Click(object sender, EventArgs e)
    {
        String username = (String)Session["username"];

        string filePath = FileUpload1.PostedFile.FileName;
        string filename = Path.GetFileName(filePath);
        string ext = Path.GetExtension(filename);

        string contenttype = String.Empty;

        switch (ext)
        {
            case ".jpg":
                contenttype = "image/jpg";
                break;
        }
        if (contenttype != String.Empty)
        {
            Stream fs = FileUpload1.PostedFile.InputStream;

            BinaryReader br = new BinaryReader(fs);

            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

            //insert the file into database
            string strQuery = "Update LoginRegisterOthers Set profilepic = @Data Where username = '" + username + "'";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
            InsertUpdateData(cmd);
            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Text = "Profile Updated.";

            Response.Redirect("MemberProfile.aspx");
        }
        else if (contenttype == String.Empty)
        {
            lblMessage.Text = "Please select your image before uploading!";
        }
        else
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "File format not recognised." + " Upload Image formats";
        }
    }

  private Boolean InsertUpdateData(SqlCommand cmd)
    {
        SqlConnection con = new SqlConnection("Data Source=localhost; Initial Catalog=project; Integrated Security=True");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            return false;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }
    }

【问题讨论】:

  • 您也应该在 UPDATE 查询中为您的用户名使用 参数
  • @marc_s 即使我使用参数作为用户名,它仍然不起作用。

标签: c# sql-server-2008 file-upload varbinarymax


【解决方案1】:

试试这个:

...

//insert the file into database

string strQuery = "Update LoginRegisterOthers Set profilepic = (SELECT BULKCOLUMN FROM OPENROWSET(BULK N'"+filename+"',  SINGLE_BLOB) AS FIle_picture)  Where username = '" + username + "'";

...

你可以直接用sql加载文件。

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2017-09-12
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    相关资源
    最近更新 更多