Download file from webservice - in ASP.NET site - c#

I want to push a file to the browser from a website using a webservice. I'm currently reading the file into a base64 byte array, and returning that from the webservice. This webservice is called from a website, and i'm stuck on how to push this as the original file to the browser. Ideally I would like to read the byte array into a memory stream, and then just write it to the Response stream if possible so the end user just downloads the file.

First, rather than send a base64 byte array, have your web service simply return a byte array for your file. Response.OutputStream.Write() will automatically base64 encode your bytes, so you might as well have them un-encoded in your memory stream.
Second, you'll need more than just the bytes. You'll need meta-data associated with the file. For the snippet below, I've placed all of that metadata into a separate class (local instance named "file"). Then, just use this snippet, once you have the data you need:
Response.Clear();
Response.ClearHeaders();
Response.ContentType = file.ContentType;
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.FileName + "\"");
Response.AddHeader("Content-Length", file.FileSize.ToString());
Response.OutputStream.Write(file.Bytes, 0, file.Bytes.Length);
Response.Flush();
Response.End();

It's possible, you'll need to make sure you explicitly set the ContentType of the HttpResponse, for example:
Response.ContentType = "image/jpeg";
Response.OutputStream.Write(buffer, 0, buffer.Length);
If you want to control the file name, you'll have to add a Content-Disposition header. Google can help you find the right way to sort that out.

Its usually a bad idea to embed a file in a web service. You just add overhead and complexity with no real benefit.
Instead you should provide a IHttpHandler to handle the file upload. Most web servers also provide helper API's to simplify this, e.g. in ASP.NET you can access the uploaded file with:
HttpContext.Request.Files[0]
There are plenty of javascript file upload scripts that simplify this on the client:
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

It really depends on the interface to your webservice. Ie SOAP, REST, ASPX.
One thing you can try is to change the content-type in your Response to "Application/octet-stream". Or something similar to tell the receiver the MIME type.
If your using WCF rest you can use Stream as a return type on the web service.

Related

Forward files from internal server to HTTP request

Maybe the title I have does not reflect my Question 100% but I will try to make it clearer. That is how our system is right now.
We have an Webserver that is public on the internet and the Webserver that has access to a Fileserver. We would like without having files on the Webserver the client to be able to download files from the Fileserver. Is there any technology available for these kind of requests?
We are using ASP. NET WebForms.
Thanks in advance.
I don't know of any Framework that would do this but I implemented something similar. In our case we have a list of the files that users should be able to download in a database but you could simply use System.IO.Directory to query for the available files in a certain folder yourself. It's also required that the application runs in an application pool that has an identity (User) that is allowed to access the fileshare.
The actual download is implemented as an ASP.Net WebHandler (.ashx-File). When the user hits that Handler I basically do something like this in the ProcessRequest method:
string fileName = "\\\\myServer\\folder\\file.pdf";
byte[] fileContent = System.IO.File.ReadAllBytes(fileName);
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(fileName));
context.Response.AddHeader("Content-Length", fileContent.Length.ToString());
context.Response.BinaryWrite(fileContent);
Of course if you are dealing with bigger files you might want to not load the entire file into memory but rather read in chunks and make multiple calls to BinaryWrite. You also should set the ContentType to a MIME-Type that fits your file type so it gets handled correctly by the clients browser.

How do I view the JSON from a WCF service?

I have set up a WCF service. I have programmed the URL to be in the format:
http://localhost:64136/NewsProvider.svc/Rest/Getnews/1
When I set the return type to be XML I can change the number at the end of that link and browse the xml in a browser. However when I change it to JSON as soon as I hit the page in firefox I am asked do I want to download it?
How do I get round this and just view the pure JSON. When I used to write a page that wrote JSON I would add the following:
Response.Clear();
Response.ContentType = "text/plain";
Response.Write(json);
Response.End();
But I dont see how to change the content type and mess with the response object with WCF?
And will changing the content type actually let me just view the raw xml in the browser what govers this?
Yes firefox will offer you to open or download the content and if you do it you will see the passed JSON. If you don't like it you should install some Firefox extension (like JSONView) or HTTP proxy (like Fiddler).

How to make a video or audio file HTTP response always download instead of play in browser?

Have some audio and video files that users are to download, however depending on the file type or browser the browser may attempt to play the file instead of downloading it. This is not desired, how can I avoid this? The anchor will be a direct link to the file unless I need to create some sort of Action to handle this properly. I am using C# ASP.NET MVC.
The important parts are setting the response headers. Set both the content-type header and the content-disposition header. Here is an example:
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)
Response.AddHeader("Content-Length", lenOfFile)
Response.ContentType = "application/octet-stream"
You'll have to set the Content-Disposition HTTP header to 'attachment':
Content-Disposition: attachment; filename="file.ext"

Display PDF - Application Page SharePoint

I am working on a Custom WebPart, for which I need an application page to render a PDF file.
I am currently using following link http://support.microsoft.com/kb/306654
It works fine in ASP.NET, but gives a blank page in SharePoint.
Here's the code:
(PDF file is in same directory)
Response.ClearContent();
Response.ClearHeaders();
//Set the appropriate ContentType.
Response.ContentType = "Application/pdf";
//Get the physical path to the file.
string FilePath = MapPath("Test.pdf");
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.Flush();
Response.End();
Working on it for last few hrs, making me crazy...any ideas?
A few ideas:
If the file is in the SharePoint directories, why not just redirect to a URL for it?
If you use Fiddler (or Firebug) to look at the HTTP traffic -- do you see the content-type change? What is the content (is it a PDF?)
The main differences between SharePoint and ASP.NET (assuming that you are getting to the file correctly) is that the page life-cycle is slightly different and the security model. You might want to look at how Reponse.End() works to make sure it isn't different in SharePoint. You can run SharePoint in verbose logging and then use .NET Reflector on the SharePoint dlls (with the logs as a guide) to see if there's some weird way of handling this. The SharePoint dlls have pretty liberal log calls. More info here: http://www.andrewconnell.com/blog/archive/2008/06/11/SharePoint-Debugging-and-Logging-Tips-and-Tricks.aspx
Have you considered rasterizing the PDF and just showing it inline in the page? This is what we do in a project my company is working on to view PDF and other documents in SharePoint (Vizit). You still have to solve your problem of reading the file, but instead of responding with the PDF, you respond with a PNG and request inside of an <img> tag.

How can I stream documents via a webservice?

I am developing a broker service which accepts a clients request to search for an image with certain tags. I have an existing web service in C# 2.0 which delivers the requested info and due to business rules, I cannot expose my 2.0 webservice to the new client and hence the need for my broker service which will invoke my 2.0 webservice and obtain the handle/location to the image and then try to stream it as the output of the WCF service call
The images could be between 1MB to 20MB in size. What is the best way to stream this data in WCF?
use MTOM attachments. See this article for a comparison and explanation: http://msdn.microsoft.com/en-us/library/ms733742.aspx
Change your response type and write your file
Response.ContentType = "image/jpeg";
Response.WriteFile(fileNameAndPath);
Response.End();
alternatively if you have the image loaded in memory
Response.ContentType = "image/jpeg";
Response.OutputStream.Write(imageBytes, 0, bytesLength);
Response.End();

Categories

Resources