下载的PDF文件无法打开
本文关键字:文件 PDF 下载 | 更新日期: 2023-09-27 18:11:06
我通过以下代码在数据库中保存pdf文件
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string filetype = Path.GetExtension(FileUpload1.PostedFile.FileName);
int filesize = FileUpload1.PostedFile.ContentLength;
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] content = br.ReadBytes((Int32)fs.Length);
Objects.Insert_FilesToDatabase(filename, filetype, content,filesize);
,然后,我试图保存文件从数据库通过点击链接通过以下代码。
void lnkDownload_Click(object sender, EventArgs e)
{
string filetype = Objects.GetFileType(Convert.ToInt32(txtslno.Text.Trim()));
string filename=Objects.GetFileName(Convert.ToInt32(txtslno.Text.Trim()));
int filesize = Objects.GetFileLength(Convert.ToInt32(txtslno.Text.Trim()));
byte[] bytfile = new byte[filesize+1000];
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",attachment;filename="+filename+".pdf");
Response.BufferOutput = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytfile);
Response.End();
}
通过这段代码,我能够下载pdf文件,但我无法打开pdf文件。错误是文件没有正确解码。你能告诉我哪里做错了吗?
我通过下面的代码解决了这个问题。
byte[] bytfile = Objects.GetFile(Convert.ToInt32(txtslno.Text.Trim()));
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename="+filename);
Response.AddHeader("Content-Length", bytfile.Length.ToString());
Response.OutputStream.Write(bytfile, 0, bytfile.Length);
Response.Flush();
Response.End();
我只是不写二进制内容到输出pdf流在我以前的代码。感谢您的支持