ASP.NET 2.0 在网页显示图片报错
-
2009年4月20日 12:39
我想在一个网页上把数据库里面的图片显示出来,但是编译器报告“System.ArgumentOutOfRangeException: 指定的参数已超出有效值的范围。 参数名:offset”。
代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;public partial class showphotoaspx : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["id"];
if (id == null)
id = "1";
using (SqlConnection con = new SqlConnection(DBcon.GetSqlCon()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT 会员照片 FROM tb_Photo WHERE 照片编号=" + id;
con.Open();
byte[] p = (byte[])cmd.ExecuteScalar();
con.Close();
Response.BinaryWrite(p); // 出错语句
}
}
}
全部回复
-
2009年4月23日 2:16版主
你好
你的代码我已经测试过,没有错误。
所以你debug下,看看你是否取到了该图片。byte【】p是否为null。
Microsoft Online Community Support- 已标记为答案 KeFang ChenModerator 2009年4月24日 9:51
-
2009年4月24日 0:20版主
支持KeFang
Object pic = cmd.ExecuteScalar();
if(pic != null)
{
byte[] p = (byte[])pic ;
Response.BinaryWrite(p);
}
con.Close();
另外。文档中说:
SqlCommand. . :: . ExecuteScalar Method 的返回值:
The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.
返回值有字符限制?建议换成SqlDataReader试试看
另外,确保你的 会员照片字段保存的是二进制内容,并且保证你真的存进去了。
你可以参考http://dotnet.aspx.cc 看一些保存和显示的例子
孟宪会- 已编辑 孟宪会MVP, Moderator 2009年4月24日 0:29
- 已标记为答案 KeFang ChenModerator 2009年4月24日 9:51
-
2009年5月19日 10:18谢谢两位老师! 这个问题我已经找到了原因所在。如果我不用AJAX的话,代码运行正常;
假如我使用AJAX控件的话,就会出现异常“System.ArgumentOutOfRangeException: 指定的参数已超出有效值的范围。 参数名:offset”。
我想请问各位老师,这是为什么呢? 我的开发环境是VS2005 + AJAX1.0 -
2009年5月19日 22:41我的看法是1. 不要在页面中直接读取数据库,然后用BinaryWrite这种方式去输出。正如你看到的那样,如果页面没有其他的东西,那么可能是没有问题的,但如果页面混杂了AJAX,则可能会有所影响。2. 那么,如果不用Binarywrite的方式,该如何输出图片呢?我们的做法是:用img标签,指定其路径为一个ashx文件(一般处理程序)。至于如何在ashx中输出图片,网上这方面的例子很多,请搜索一下3. 有些图片格式,例如(bmp),在输出的时候,需要编写偏移量。
-
2009年5月20日 3:08
恩,明白了。 谢谢