我正在使用 html 标签制作文件上传器。我的表中有 id、Name 和 Data。数据以二进制格式将文件的内容存储在 datatype 列中varbinary(max)
。我能够成功上传文件,并且还能够读回字节数组。
在后面的代码上传代码:
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into FileUploader2 values (@Name, @ContentType, @Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Context.Response.Write("Uploaded Successfully!");
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
我还在创建一个网格,它向我显示文件列表以及一个图标,单击该图标将在读取字节数组后查看文件。我在 onclick 上有一个 JS 函数,我通过代码隐藏的 WebMethod 访问它。以下是用户单击查看图标时的代码:
[System.Web.Services.WebMethod]
public static void ShowDocument()
{
string filename = string.Empty;
string contentType = string.Empty;
byte[] bytes = null;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
using (SqlCommand com = new SqlCommand("SELECT * FROM FileUploader2", con))
{
using (SqlDataReader reader = com.ExecuteReader())
{
if (reader.Read())
{
filename = (string)reader["Name"];
contentType = (string)reader["ContentType"];
bytes = (byte[])reader["Data"];
}
}
}
}
System.Web.HttpContext.Current.Response.ContentType = contentType;
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;
filename=" + filename);
System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
System.Web.HttpContext.Current.Response.Flush();
}
此代码也可以正常工作,并且可以正确读取所有列。现在阅读后,我也想在弹出窗口中查看该文件。我该怎么做?我想我必须使用 contenttype 让它知道我想打开什么类型的文件,然后使用字节来这样做。但我不知道如何实现这一目标。