Opening a pdf file in asp.net c# - c#

I am using the following piece of code to open a PDF file that I have just created this methods works in one section on my site but it does not seem to redirect to the PDF from another section of my site. What could possible be the reason why the PDF file is not opening.
Context.Response.Buffer = false;
FileStream inStr = null;
byte[] buffer = new byte[1024];
long byteCount;
inStr = File.OpenRead(pdfPath);
while ((byteCount = inStr.Read(buffer, 0, buffer.Length)) > 0) {
if (Context.Response.IsClientConnected) {
Context.Response.ContentType = "application/pdf";
Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
Context.Response.Flush();
}
}

Your pdf path is relative.
You could also read the file in one shot
bytez=File.ReadAllBytes(Server.MapPath(pdfPath))
And send it the same way. Response.BinaryWrite(bytez).

Related

Streaming video to embedded VLC via ASP.Net - Unable to seek position

I am trying to write a video streaming site using an embedded VLC control to play the video and an asp.net handler to get the video stream. I am embedding the control as follows:
<embed type="application/x-vlc-plugin" pluginspage="http://www.videolan.org" width="640" height="480" target="http://MyWebsite/MyHandler.ashx"/>
<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" codebase="http://download.videolan.org/pub/videolan/vlc/last/win32/axvlc.cab"></object>
And the code i am using in the handler to stream the video is:
public void ProcessRequest(HttpContext context)
{
context.Response.Buffer = false;
context.Response.ContentType = "text/plain";
var path = #"c:/file.avi";
var file = new FileInfo(path);
var len = (int)file.Length;
context.Response.AppendHeader("content-length", len.ToString());
var buffer = new byte[1024];
var outStream = context.Response.OutputStream;
using (Stream stream = File.OpenRead(path))
{
int bytes;
while (len > 0 && (bytes = stream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, bytes);
len -= bytes;
}
}
}
While this works and streams the video, I am unable to seek back or forward, the seek bar doesn't move at all. I thought since I sent the file size it would be able to calculate positions but I guess not. Is it possible to seek in the video or will it not be possible since it is a stream (even though it is not a 'true' stream since it is coming from a file with a defined size etc)

Download multiple Mp3 files from different urls as zip archive in asp.Net

I am working on a .Net Application in which i need to add multiple mp3 files to a zip archive and download the zip archive locally. The mp3 files are on different urls ad are not hosted or stored on my server. Which library is good for such thing. I tried using SharpLipZip but failed. Here is my code which i am currently trying to use with sharpziplib. All the code is executed but browser doesnt download.
string[] fileURLs = new string[] { "http://www.musicimpressions.com/demos_mp3g/d_RE41843.mp3", "http://media.archambault.ca/sample/6/2/B/0/62B0CC2D91D4357D6477845E967AF9BA/00000000000000027923-256K_44S_2C_cbr1x_clipped.mp3" };
Response.AddHeader("Content-Disposition", "attachment; filename=CallRecordings.zip");
Response.ContentType = "application/x-zip-compressed";
ZipOutputStream zipStream = new ZipOutputStream(Response.OutputStream);
zipStream.SetLevel(3);
byte[] buffer = new byte[10485760];
foreach (string url in fileURLs)
{
Stream fileStream = null;
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
fileStream = fileResp.GetResponseStream();
byte[] fileBytes = ReadStream(fileStream);
ZipEntry fileEntry = new ZipEntry(ZipEntry.CleanName(url));
fileEntry.Size = fileBytes.Length;
zipStream.PutNextEntry(fileEntry);
zipStream.Write(fileBytes, 0, fileBytes.Length);
Response.Flush();
fileStream.Close();
}
zipStream.Finish();
zipStream.Flush();
zipStream.Close();
Response.Flush();
Response.End();
The definition of ReadStream is as follows.
public static byte[] ReadStream(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Well, thats the same thing which I am also building for my website, anyhow i was trying to look for the zip file structure first to create the zip file manually instead of using any other library. Until now, i am only able to get the structure of the zip file :
https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html
Here, it mentions that you need to have the CRC32 of the file first which is being appended to the zip file, so thats the tricky part in my side. Let me know once you gets any updates for the same.
Good Luck :)

Return PDF to WebPage from ASHX

I have a web page with a "download" link on it.
Using jQuery I do an Ajax Get to a ASHX file.
In the ASHX I get the Stream of the file. I then convert the stream to a byte array and return the byte array back to the calling html page;
jQuery
$(".DownloadConvertedPDF").click(function () {
var bookId = $(this).attr("bookId");
$.get('/UserControls/download.ashx?format=pdf&bookId=' + bookId, {}, function (data) { });
});
C#
context.Response.ContentType = "Application/pdf";
Stream fileStream = publishBookManager.GetFile(documentId);
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
}
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
I don't get an error but also the PDF doesn't display on screen.
Ideally I'd like the pdf returned and the jQuery to launch the pdf in a seperate tab within the browser.
How can I make this happen or what am I doing wrong?
Try this (do not use .get):
window.open('/UserControls/download.ashx?format=pdf&bookId=' + bookId, "pdfViewer");
To prevent the "File does not begin with '%PDF" error, use Response.BinaryWrite:
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.ContentType = "application/pdf";
Stream fileStream = publishBookManager.GetFile(documentId);
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
}
context.Response.BinaryWrite(data);
context.Response.Flush();
Through use of context.Response.TransmitFile, a more concise way to serve a PDF from an ashx web handler is:
context.Response.Clear();
context.Response.ContentType = "application/pdf";
string filePath = System.Web.HttpContext.Current.Server.MapPath(#"~\path-to\your-file.pdf");
context.Response.TransmitFile(filePath);
i am also using window.open for getting the pdf. but it is always displayed while try to use same URL through address bar directly without logged in. how to solve this one.

Write PDF stream to response stream

If I have a pdf file as a Stream, how can I write it to the response output stream?
Since you are using MVC, the best way is to use FileStreamResult:
return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = "file.pdf"
};
Playing with Response.Write or Response.OutputStream from your controller is non-idiomatic and there's no reason to write your own ActionResult when one already exists.
One way to do it is as follows:
//assuming you have your FileStream handle already - named fs
byte[] buffer = new byte[4096];
long count = 0;
while ((count = fs.Read(buffer, 0, buffer.Length)) > 0)
{
response.OutputStream.Write(buffer, 0, count);
response.Flush();
}
You can also use GZIP compression to speed the transfer of the file to the client (less bytes streamed).
In asp.net this is the way to download a pdf file
Dim MyFileStream As FileStream
Dim FileSize As Long
MyFileStream = New FileStream(filePath, FileMode.Open)
FileSize = MyFileStream.Length
Dim Buffer(CInt(FileSize)) As Byte
MyFileStream.Read(Buffer, 0, CInt(FileSize))
MyFileStream.Close()
Response.ContentType = "application/pdf"
Response.OutputStream.Write(Buffer, 0, FileSize)
Response.Flush()
Response.Close()
The HTTP Response is a stream exposed to you through the HttpContext.Response.OutputStream property, so if you have the PDF file in a stream you can simply copy the data from one stream to the other:
CopyStream(pdfStream, response.OutputStream);
For an implementation of CopyStream see Best way to copy between two Stream instances - C#
Please try this one:
protected void Page_Load(object sender, EventArgs e) {
Context.Response.Buffer = false;
FileStream inStr = null;
byte[] buffer = new byte[1024];
long byteCount; inStr = File.OpenRead(#"C:\Users\Downloads\sample.pdf");
while ((byteCount = inStr.Read(buffer, 0, buffer.Length)) > 0) {
if (Context.Response.IsClientConnected) {
Context.Response.ContentType = "application/pdf";
Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
Context.Response.Flush();
}
}
}

Uploading docx corrupts file

I am using the code below to upload a file. The files upload without error, but when I open a file with a .docx extension M$ says that the file is corrupted. It is able to repair the file and then open, however. I'd like to fix this so the document opens correctly.
string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = #"C:\" + Guid.NewGuid().ToString() + strExtension;
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
byte[] bytes = new byte[16 * 1024];
int bytesRead;
while ((bytesRead = context.Request.InputStream.Read(bytes, 0, bytes.Length)) > 0)
{
fs.Write(bytes, 0, bytesRead);
}
}
Thanks.
EDITED:
File saves correctly with this code:
while ((bytesRead = context.Request.Files[0].InputStream.Read(bytes, 0, bytes.Length)) > 0)
Also saves correctly with context.Request.Files[0].SaveAs(...);
It looks like you are reading the HttpRequest.InputStream. The better thing to do is check the HttpRequest.Files collection.
(Or even easier, use a FileUpload server control).
Your code is copying the raw input, which is most likely multi-part, to a file.
This doesn't answer your question exactly, but you could use HttpPostedFile.SaveAs to save the content to the desired path.
string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = #"C:\" + Guid.NewGuid().ToString() + strExtension;
context.Request.Files[0].SaveAs(fileName); // i'll ignore the violation of the law of demeter ;)

Categories