我之前问了一个关于从数据库中检索pdf文件的问题,并得到了我的问题的答案。尽管该代码早先为我工作,但我目前无法检索文件内容,只能从数据库中检索文件名(如:
"%PDF-1.4 1 0 obj <</AcroForm <</DR <</Font <</Helvetica 220 0 R>> /ProcSet [/PDF /Text]>> /Fields ")
。
这是我的代码:
SqlCommand cmd1 = new SqlCommand("select Docdata from SaveDoc where DocID='"
+ TextBox1.Text + "'",con);
con.Open();
byte[] b = null;
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da = new SqlDataAdapter(cmd1);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
b = Encoding.ASCII.GetBytes(dt.Rows[0][0].ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(b);
}
我上传的代码:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string fileExtension =
Path.GetExtension(FileUpload1.PostedFile.FileName);
string documentType = string.Empty;
switch (fileExtension)
{
case ".pdf":
documentType = "application/pdf";
break;
case ".xls":
documentType = "application/vnd.ms-excel";
break;
case ".xlsx":
documentType = "application/vnd.ms-excel";
break;
case ".doc":
documentType = "application/vnd.ms-word";
break;
case ".docx":
documentType = "application/vnd.ms-word";
break;
case ".gif":
documentType = "image/gif";
break;
case ".png":
documentType = "image/png";
break;
case ".jpg":
documentType = "image/jpg";
break;
}
int fileSize = FileUpload1.PostedFile.ContentLength;
byte[] documentBinary = new byte[fileSize];
FileUpload1.PostedFile.InputStream.Read(documentBinary, 0, fileSize);
string CommandText = "INSERT INTO SaveDoc(DocName,DType,DocData)" +
" VALUES (@DocName,@Type,@DocData)";
SqlCommand cmd = new SqlCommand(CommandText, con);
SqlParameter DocName =
new SqlParameter("@DocName", SqlDbType.VarChar, 50);
DocName.Value = fileName.ToString();
cmd.Parameters.Add(DocName);
SqlParameter Type = new SqlParameter("@Type", SqlDbType.VarChar, 50);
Type.Value = documentType.ToString();
cmd.Parameters.Add(Type);
SqlParameter uploadedDocument =
new SqlParameter("@DocData", SqlDbType.Binary, fileSize);
uploadedDocument.Value = documentBinary;
cmd.Parameters.Add(uploadedDocument);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
lblMessage.Text = "File saved to database";
//GridView1.DataBind();
}
}
在数据库中,字段为varchar
。