c# - 下载的pdf文件打不开

标签 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);

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

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

关于c# - 下载的pdf文件打不开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223154/

相关文章:

javascript - 当 Json 长度太长时,Ajax 调用 ASP.NET MVC Controller 返回 404

c# - 正确转义 URI 以在 HttpClient.PostAsync 中使用需要什么?

asp.net - 合并 3 个 CSS 文件的工具

c# - LINQ 搜索相似字符串(名称)

c# - 如何获取货币分数名称?

c# - 带有 POST Controller 操作的 ASP.NET MVC OutputCache

wpf - Teststack.White拖放问题

c# - 如何限制泛型参数具有特定的静态函数?

c# - 如何在运行时在 WinForm 中添加按钮?

c# - Linq 查询以匹配 xml 中的字符串值