2

我通过以下代码将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 文件。错误是文件未正确解码。你能帮我看看我哪里出错了吗?

4

1 回答 1

2

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

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

于 2013-04-26T15:24:11.710 回答