文件上传下载出现Byte[]和string的转换失败

netstudy0105 2012-02-21 01:26:49
错误:
上传错误:将参数值从 Byte[] 转换到 String 失败
下载错误:无法将类型为“System.String”的对象强制转换为类型“System.Byte[]”。
代码如下:
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.databindTodg();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (this.fileUpload.PostedFile.FileName == "")
{

Response.Write("<script language=javascript>alert('不能上传空文件')</script>");
return;
}

else
{
try
{
string path = Server.MapPath("upload/");//保存上传文件的文件夹upload虚拟路径对应的实际路径
string filePath = this.fileUpload.PostedFile.FileName;//客户端文件的完全限定名
string serverPath = path + filePath.Substring(filePath.LastIndexOf("//") + 1);//上传的文件保存在服务器端的路径
string fileName = filePath.Substring(filePath.LastIndexOf("//") + 1);//文件名
string fileType = this.fileUpload.PostedFile.ContentType.ToString();//文件类型
System.IO.Stream streamFile = this.fileUpload.PostedFile.InputStream;//建立数据流对象
int fileLength = this.fileUpload.PostedFile.ContentLength;//文件长度以字节为单位
byte[] fileData = new Byte[fileLength];//新建一个数组
streamFile.Read(fileData, 0, fileLength);//将这个数据流读取到数组中


SqlConnection conn;
SqlCommand cmd;
string cmdString = @"Insert gerenjianli(fileName,filePath,fileType,fileDate)
Values (@fileName,@filePath,@fileType,@fileData)";
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["schoolhoomConnectionString"].ConnectionString);
cmd = new SqlCommand(cmdString, conn);
cmd.CommandType = CommandType.StoredProcedure;//指定类型
cmd.Parameters.Add("@fileName", SqlDbType.VarChar);
cmd.Parameters["@fileName"].Value = fileName;
cmd.Parameters.Add("@filePath", SqlDbType.VarChar);
cmd.Parameters["@filePath"].Value = serverPath;
cmd.Parameters.Add("@fileType", SqlDbType.VarChar);
cmd.Parameters["@fileType"].Value = fileType;
cmd.Parameters.Add("@fileData", SqlDbType.NText);
cmd.Parameters["@fileData"].Value = fileData;
conn.Open();

cmd.ExecuteNonQuery();
conn.Close();


}


catch (Exception ex)
{
Response.Write(ex.Message);
}

Response.Write("<script language=javascript>alert('文件上传成功!')</script>");
}
}


private void databindTodg()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["schoolhoomConnectionString"].ConnectionString);
con.Open();
string sql = "select * from gerenjianli";
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
sda.Fill(ds);
this.GridView1.DataSource = ds.Tables[0].DefaultView;
this.DataBind();
}




protected void Button2_Click(object sender, EventArgs e)
{

}
protected void btnDownLoad_Click(object sender, EventArgs e)
{

}


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int fileID = Convert.ToInt32(e.CommandArgument.ToString());
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["schoolhoomConnectionString"].ConnectionString);
con.Open();
string sql = "select * from gerenjianli where fileID='" + fileID + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
Response.Buffer = true;
Page.Response.Clear();//清除缓冲区所有内容
Page.Response.ContentType = "application/octet-stream";
Page.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(sdr["fileName"].ToString()));
byte[] file = (Byte[])sdr["fileData"];//读出数据
int a = file.Length;
Response.BinaryWrite(file);
Response.Flush();
Response.End();
sdr.Close();
con.Close();
}
}
...全文
329 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
孟子E章 2012-02-21
  • 打赏
  • 举报
回复
加上
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
试试

如果是迅雷下载,下载完毕后会自动改成doc的
netstudy0105 2012-02-21
  • 打赏
  • 举报
回复
现在下载的是网页asp文件,我的意思是让下载成.doc或者.txt文件,谢谢大哥,辛苦了
孟子E章 2012-02-21
  • 打赏
  • 举报
回复
你加上
Page.Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(sdr["fileName"].ToString()));
byte[] file = (Byte[])sdr["fileData"];//读出数据
int a = file.Length;
Response.AddHeader("Content-Length",a.ToString());
Response.BinaryWrite(file);

我想判断是.txt或者是.doc?
使用 fileType 判断

没有8000的限制
netstudy0105 2012-02-21
  • 打赏
  • 举报
回复
还有问题就是这样是不是只能上传8000个字节的文件,如果要大点的文件数据库是不是不支持,如果是binnary类型的话
netstudy0105 2012-02-21
  • 打赏
  • 举报
回复
fileData写成fileData已经改过来了
fileData类型是binnary
还有就是这2行应该怎么处理,这个是下载成asp文件,我想判断是.txt或者是.doc,上传时候只允许上传这2中文件
Page.Response.ContentType = "application/octet-stream";
Page.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(sdr["fileName"].ToString()));
孟子E章 2012-02-21
  • 打赏
  • 举报
回复
string cmdString = @"Insert gerenjianli(fileName,filePath,fileType,fileDate)
Values (@fileName,@filePath,@fileType,@fileData)";

你的数据库字段名称 fileDate写错了吧?

另外你的 fileData 字段是image或者binnary类型的吗?

(Byte[])sdr["fileData"];/
netstudy0105 2012-02-21
  • 打赏
  • 举报
回复
照你6楼的写法,出现错误
不能创建大小为 8087 的行,该大小大于所允许的最大行大小 8060。语句已终止。
如果我直插入fileData的话不会报错,不知道为什么,谢谢大哥
观光客 2012-02-21
  • 打赏
  • 举报
回复
byte[] file = (Byte[])sdr["fileData"];//读出数据
这一句有没有错?
孟子E章 2012-02-21
  • 打赏
  • 举报
回复
你写
string cmdString = @"Insert gerenjianli(fileName,filePath,fileType,fileDate)
Values (@fileName,@filePath,@fileType,@fileData)";
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["schoolhoomConnectionString"].ConnectionString);
cmd = new SqlCommand(cmdString, conn);
cmd.Parameters.AddWithValue("@fileName", fileName);
cmd.Parameters.AddWithValue("@filePath", serverPath);
cmd.Parameters.AddWithValue("@fileType", fileType);
cmd.Parameters.AddWithValue("@fileData", fileData);
conn.Open();

cmd.ExecuteNonQuery();

进行简化
孟子E章 2012-02-21
  • 打赏
  • 举报
回复
下载的方法

fileID 是数字不加引号的,非数字需要加
int fileID = Convert.ToInt32(e.CommandArgument.ToString());
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["schoolhoomConnectionString"].ConnectionString);
con.Open();
string sql = "select * from gerenjianli where fileID=" + fileID;
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sdr = cmd.ExecuteReader();
if(sdr.Read())
{
Response.Buffer = true;
Page.Response.Clear();//清除缓冲区所有内容
Page.Response.ContentType = "application/octet-stream";
Page.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(sdr["fileName"].ToString()));
byte[] file = (Byte[])sdr["fileData"];//读出数据
int a = file.Length;
Response.BinaryWrite(file);
Response.Flush();
Response.End();
}
sdr.Close();
con.Close();
孟子E章 2012-02-21
  • 打赏
  • 举报
回复
你使用的是SQL语句,怎么指定为存储过程呢?能找到吗

cmd.CommandType = CommandType.StoredProcedure;//指定类型
这行删除啊
netstudy0105 2012-02-21
  • 打赏
  • 举报
回复
下载还是那个错误
netstudy0105 2012-02-21
  • 打赏
  • 举报
回复
上传改成cmd.Parameters.Add("@fileData", SqlDbType.Binary);

提示 找不到存储过程 ''。
孟子E章 2012-02-21
  • 打赏
  • 举报
回复
cmd.Parameters.Add("@fileData", SqlDbType.NText);
应该是
cmd.Parameters.Add("@fileData", SqlDbType.Image);

或者
cmd.Parameters.Add("@fileData", SqlDbType.Binary);

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧