Pdf looks empty in browser from ftp in ASP.net

2019-09-15 19:06发布

问题:

I want to show pdf files in browser which come from ftp. I found some code and I've tried it. The pdf is displayed in the browser but the file is empty. It has all of the pages as the original file but does not have the content on pages.

string filename = Request.QueryString["view"];    
FileInfo objFile = new FileInfo(filename);

System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + objFile.Name));
request.Credentials = new NetworkCredential(Ftp_Login_Name,Ftp_Login_Password);

System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(responseStream);

Stream responseStream = response.GetResponseStream();
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentEncoding = reader.CurrentEncoding;
Response.ContentType = "application/pdf";            
Response.AddHeader("Content-Disposition", "inline; filename=" + Request.QueryString["name"]);
Response.Write(reader.ReadToEnd());
Response.End();

How can I show it in the browser correctly? http://i.stack.imgur.com/8weMr.png

回答1:

Try this:

FileInfo objFile = new FileInfo(filename);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + filename));
request.Credentials = new NetworkCredential(Ftp_Login_Name, Ftp_Login_Password);

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);

byte[] bytes = null;
using (var memstream = new MemoryStream())
{
    reader.BaseStream.CopyTo(memstream);
    bytes = memstream.ToArray();
}

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline; filename=" + objFile.Name);
Response.BinaryWrite(bytes);
Response.End();


回答2:

Response.Write is used for sending text to the client. A PDF file contains binary content so the content may be converted incorrectly.

Use Response.BinaryWrite instead. Additionally in your code, you are not sending the file. Try this:

FileStream fs = File.OpenRead(filename);

int length = (int)fs.Length;
BinaryReader br = new BinaryReader(fs);
byte[] buffer = br.ReadBytes(length);

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentEncoding = reader.CurrentEncoding;
Response.ContentType = "application/pdf";            
Response.AddHeader("Content-Disposition", "inline; filename=" + Request.QueryString["name"]);
Response.BinaryWrite(buffer);