I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

Error while viewing PDF document in browser

I am trying to view PDF/doc/img file in browser but getting error:

Unable to load PDF document

Code:

private readonly IServiceContext _ctx;
public void View(string guid)
{
    var stream = null as Stream;
    repo.GetFileStream(fileName, filePath, out stream);
    if (stream.CanSeek)
    {
        stream.Seek(0, SeekOrigin.Begin);
    }
    _ctx.reqObj.HttpContext.Response.ContentType = "application/pdf";
    _ctx.reqObj.HttpContext.Response.Headers.Add("Content-Disposition", "inline; filename=" + fileName);
    _ctx.reqObj.HttpContext.Response.Body = stream;
}

Repo:

public void GetFileStream(string fileName, string filePath, out Stream stream)
{
    stream = new MemoryStream();
    using (var fileStream = File.OpenRead(Path.Combine(filePath, fileName)))
    {
        if (fileStream.CanSeek) fileStream.Seek(0, SeekOrigin.Begin);

        fileStream.CopyTo(stream);
    }
}

Browser Request:

enter image description here

I just want to allow user to view the content of file in browser and not DOWNLOAD.

I will appreciate any help:)

Update : enter image description here

enter image description here

Upvotes: 2

Views: 86

Answers (1)

Nkosi
Nkosi

Reputation: 247088

Content length of the response is zero (0) according to response headers in the provided image.

Consider adding the header to the response.

public void View(string guid) {
    var stream = null as Stream;
    repo.GetFileStream(fileName, filePath, out stream);
    if (stream.CanSeek) {
        stream.Seek(0, SeekOrigin.Begin);
    }
    var response = _ctx.reqObj.HttpContext.Response;
    response.ContentType = "application/pdf";
    response.Headers.Add("Content-Disposition", $"inline; filename={filename}");
    response.Headers.Add("Content-Length", stream.Length.ToString());
    response.Body = stream;
}

If the content length is still zero then you would need to review that the file being loaded has actual content to be read.

Upvotes: 2

Related Questions