简体   繁体   中英

Adding image to database along with other fields in webforms asp.net

I have a table students with columns

id primary key, firstname, lastname,picture. picture datatype is varbinary(MAX)

I am working with WebForms in ASP.NET.

I have this stored procedure.

create procedure spAddStudents
(
    @id int,
    @firstname nvarchar(50),
    @lastname nvarchar(50),
    @picture varbinary(MAX)
)  
as  
Begin  
    insert into students
    values (@id, @firstname, @lastname,@picture)  
End

In the webform I wrote this code

string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

using (SqlConnection con = new SqlConnection(CS))
{
    if (FileUpload1.HasFile)
    {
        string filename = FileUpload1.PostedFile.FileName;
        string filepath = "Images/" + FileUpload1.FileName;
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + filename);
                       
        SqlCommand cmd = new SqlCommand("spAddStudent",con);
                                            
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@firstname", txtFirstName.Text);
        cmd.Parameters.AddWithValue("@lastname", txtLastName.Text);
        cmd.Parameters.AddWithValue("@picture",filepath);

        con.Open();
        int i = cmd.ExecuteNonQuery();

        if (i != 0)
        {
            lblMessage.Text = "Record inserted successfully";
        }
    }
}

when I gave image as datatype for picture in storedprocedure I get this error at line cmd.executeNonQuery()

Operand type clash: nvarchar is incompatible with image

when I gave varbinary(max) as datatype for picture in storedprocedure I get this error

Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.

At the moment you're trying to insert the path to the file on the hard drive (a string) into a varbinary field which is why you are getting this error. Instead skip writing the file to the hard drive, get the bytes as an array and then write that to your database field instead.

MemoryStream uploadstream = new MemoryStream();
HttpPostedFile.InputStream.CopyTo(uploadstream);
var picturearray = uploadstream.ToArray();
List<SqlParameter> Parameters = new List<SqlParameter>();
Parameters.Add(new SqlParameter("picture", picturearray ));

This code works with 'Image' as the type on the database table. It may also work with Varbinary(MAX) using Parameters.AddWithValue(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM