Pdf looks empty in browser from ftp in ASP.net

喜你入骨 提交于 2019-12-13 06:59:19

问题


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


来源:https://stackoverflow.com/questions/26160004/pdf-looks-empty-in-browser-from-ftp-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!