Trying to stream a PDF file with asp.net is producing a “damaged file”

后端 未结 6 392
长情又很酷
长情又很酷 2020-12-16 23:51

In one of my asp.net web applications I need to hide the location of a pdf file being served to the users.

Thus, I am writing a method that retrieves its binary con

6条回答
  •  醉梦人生
    2020-12-17 00:33

    This snippet includes the code for reading in the file from a file path, and extracting out the file name:

    private void DownloadFile(string path)
    {
        using (var file = System.IO.File.Open(path, FileMode.Open))
        {
            var buffer = new byte[file.Length];
            file.Read(buffer, 0, (int)file.Length);
    
            var fileName = GetFileName(path);
            WriteFileToOutputStream(fileName, buffer);
        }
    }
    
    private string GetFileName(string path)
    {
        var fileNameSplit = path.Split('\\');
        var fileNameSplitLength = fileNameSplit.Length;
        var fileName = fileNameSplit[fileNameSplitLength - 1].Split('.')[0];
        return fileName;
    }
    
    private void WriteFileToOutputStream(string fileName, byte[] buffer)
    {
        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition",
            $"attachment; filename\"{fileName}.pdf");
        Response.OutputStream.Write(buffer, 0, buffer.Length);
        Response.OutputStream.Close();
        Response.Flush();
        Response.End();
    }
    

提交回复
热议问题