我无法从asp.net更新我的图像 [英] I am not able to update my image from asp.net

查看:52
本文介绍了我无法从asp.net更新我的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  if (FileUpload2.HasFile)
{
// 获取上传文件的长度
int length = FileUpload2.PostedFile。的ContentLength;
// 创建一个字节数组来存储二进制图像数据
byte [] imgbyte = new byte [length] ;
// 将当前选定的文件存储在memeory中
HttpPostedFile img = FileUpload2。 PostedFile;
// 设置二进制数据
img.InputStream.Read(imgbyte, 0 ,length);

// 使用web.config存储连接字符串
SqlConnection connection = new SqlConnection(strcon);
connection.Open();

SqlCommand cmd = new SqlCommand( 更新图像集Image =' + imgbyte + '其中ImageId =' + imgID + ',connection);

cmd.ExecuteNonQuery();
connection.Close();
gvImages.EditIndex = -1;
BindGridData();
}



此代码成功提交图片但从未在页面上显示

解决方案

问题是您尝试将字节数组连接到SQL语句。这将需要使用额外的语法,但总的来说,不建议将语句连接到语句。这让你开始接受SQL注入并引入转换问题,比如这个。



所以请使用 SqlParameter [ ^ ]。



代码应该类似于

 SqlCommand cmd =  new  SqlCommand( 更新图像集Image = @image,其中ImageId = @ imgid,连接); 
cmd.Parameters.AddWithValue( @ image,imgbyte);
cmd.Parameters.AddWithValue( @ imgid,imgid);
cmd.ExecuteNonQuery();



另外你应该使用使用块来正确处理命令


if (FileUpload2.HasFile)
            {
                //getting length of uploaded file
                int length = FileUpload2.PostedFile.ContentLength;
                //create a byte array to store the binary image data
                byte[] imgbyte = new byte[length];
                //store the currently selected file in memeory
                HttpPostedFile img = FileUpload2.PostedFile;
                //set the binary data
                img.InputStream.Read(imgbyte, 0, length);

                //use the web.config to store the connection string
                SqlConnection connection = new SqlConnection(strcon);
                connection.Open();

                SqlCommand cmd = new SqlCommand("Update Image set Image='" + imgbyte + "' where ImageId='" + imgID + "'", connection);

                cmd.ExecuteNonQuery();
                connection.Close();
                gvImages.EditIndex = -1;
                BindGridData();
            }


This code submit image successfully but never display on page

解决方案

The problem is that you try to concatenate the byte array to the SQL statement. This would require use of additional syntax but in overall it isn't advisable concatenate values to the statements. That leaves you open to SQL injections and introduces conversion problems such as this.

So instead, use SqlParameter[^].

The code should look something like

SqlCommand cmd = new SqlCommand("Update Image set Image= @image where ImageId=@imgid", connection);
cmd.Parameters.AddWithValue("@image", imgbyte);
cmd.Parameters.AddWithValue("@imgid", imgid);
                cmd.ExecuteNonQuery();


Also you should use a using block to properly dispose the command.


这篇关于我无法从asp.net更新我的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆