我使用二进制文件在SQL中保存我的word / excel / pdf / Img文件,我能够将文件成功保存为二进制文件。
var fileSize = FileUpload1.PostedFile.ContentLength;
var documentBinary = new byte[fileSize];
var u = new UDocument
{
DocName = fileName.ToString(CultureInfo.InvariantCulture),
Type = documentType.ToString(CultureInfo.InvariantCulture),
DocData = documentBinary
};
u.DocID = ++count;
sd.UDocuments.InsertOnSubmit(u);
sd.SubmitChanges();
现在,我正在尝试打开二进制文件作为他们的文档类型,我将从gridview打开它,我将显示所有存储的文件。
现在,在Gridview SelectedIndexChange事件中,我能够获取文档ID,文档名称,供我打开文件,但我不清楚如何从documentID中获取二进制数据,这是PK,并且如何写出文件。这是我试图让它起作用的方法:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int docid = Convert.ToInt16(GridView1.SelectedRow.Cells[1].Text);
string name = GridView1.SelectedRow.Cells[2].Text;
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + name);
Response.BinaryWrite(GetData(docid)); // I am unclear on how to use this method, with the
Response.Flush();
}
其中,在我的GetData(int id)方法中,我试图使用LINQ通过这样的唯一docID获取正确的二进制数据:
var data = from a in sd.UDocuments
where a.DocID == id
select a.DocData
但我不确定在此方法中使用什么返回类型。
任何帮助或指示都会很棒。
答案 0 :(得分:1)
GetData
的返回类型应与DocData
属性的类型相同,即byte[]
。
答案 1 :(得分:0)
private byte[] GetData(int id)
{
byte[] data = (from a in sd.UDocuments
where a.DocID == id
select a.DocData).First().ToArray();
return data;
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int docid = Convert.ToInt16(GridView1.SelectedRow.Cells[1].Text);
string name = GridView1.SelectedRow.Cells[2].Text;
string contentType = GridView1.SelectedRow.Cells[3].Text;
Response.Clear();
Response.ContentType = contentType; //"application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + name);
Response.BinaryWrite(GetData(docid));
Response.End();
}