下载的pdf文件未打开

时间:2013-04-25 19:27:29

标签: c# asp.net c#-4.0

我通过以下代码

在数据库中保存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);

然后,Iam尝试通过以下代码单击链接来保存数据库中的文件。

     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文件。错误是文件未正确解码。你能告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:1)

我通过以下代码解决了这个问题..

        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流。 感谢您的支持