Tuesday, November 27, 2012

Downloading files using WCF REST and viewing them in a browser

Creating a service that allows users to download a file is really not that different from creating a regular service. You just have to make sure the method returns a Stream object. This article helped me a little. 

However, you have to do one more thing, because the code in the article downloads the file instead of opening it in the browser itself. The code in the article sets the ContentType of the response to be "application/octet-stream". IE handles this correctly and if the file is an image, it's displayed in the browser. But other browsers like FF and Chrome need the correct ContentType (like "image/png") to open the file in the browser; otherwise they will prompt you to download the file (or even download it automatically). Check out the section "Unable to set an automatic action" of this Mozilla KB article for a more thorough explanation.

Therefore, you'll need to check the file extension and set the ContentType to it's correct value. Pretty simple huh?

No comments: