我正在尝试设置FileStream以在我的应用程序中工作。我很确定我遇到的问题不在我的上传代码中。如果我查看测试文件的属性,它显示为46个字节。当我通过下载命令观看调试步骤时,它获取了46字节的文件长度。
在最后一步,当文件在浏览器中实际下载时,会向文件中添加一组数据,特别是页面本身的整个HTML。我不知道为什么会发生这种事。
protected void gvFilestream_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "GetFile")
{
SqlConnection objSqlCon = new SqlConnection(CS);
objSqlCon.Open();
SqlTransaction objSqlTran = objSqlCon.BeginTransaction();
SqlCommand objSqlCmd = new SqlCommand("FileGet", objSqlCon, objSqlTran);
objSqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter objSqlParam1 = new SqlParameter("@ID", SqlDbType.VarChar);
objSqlParam1.Value = e.CommandArgument;
objSqlCmd.Parameters.Add(objSqlParam1);
string path = string.Empty;
string fileType = string.Empty;
using (SqlDataReader sdr = objSqlCmd.ExecuteReader())
{
while (sdr.Read())
{
path = sdr[0].ToString();
fileType = sdr[1].ToString();
}
}
objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);
byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();
SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);
byte[] buffer = new byte[(int)objSqlFileStream.Length];
objSqlFileStream.Read(buffer, 0, buffer.Length);
objSqlFileStream.Close();
objSqlTran.Commit();
Response.AddHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(path) + fileType);
// Here you need to manage the download file stuff according to your need
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(buffer);
}
}
这是我下载文件的代码隐藏方法。下面是下载的文本文件顶部的一个片段。我没有把整件事都放进去,因为它看起来毫无意义。原始文档仅包含"此文档为测试文档,用于测试。"
This document is a test document, for testing.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
View
</title>
我正在使用我在互联网上找到的一个指南来设置FileStream,但它并没有真正解释每个部分在做什么,所以我不知道我的方法哪里出了问题。它似乎会出现在评论区,我需要根据自己的需求进行定制。
有什么建议吗?
在将二进制内容写入输出之前,通过调用response.Clear()清除响应。
为了防止进一步写入输出,您应该立即停止请求执行:
Response.Clear();
Response.BinaryWrite(buffer);
Response.End();