Wednesday, December 22, 2010

A way to download an Aspose Word document to a browser using MVC2

Perhaps there's a better way, but here is what I did quickly to get an Aspose Word document down to a browser. In the controller class use a MemoryStream to feed a FileStreamResult.
//Controller
public ActionResult MergeAndDownload(Choice choice) {
 MemoryStream memoryStream = new MemoryStream();
 Document document = ... // get your Aspose document
 document.Save(memoryStream, SaveFormat.Docx);
 memoryStream.Position = 0;
 var fileStreamResult = new FileStreamResult(memoryStream, "application/ms-word");
 fileStreamResult.FileDownloadName = "MySuggestedFilename.docx";
 return fileStreamResult;
}
In the View just do a Model.Save()
//View
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Aspose.Words.Document>" %>
<asp:Content ID="Content1" runat=server ContentPlaceHolderID="MainContent">
<%@ Import Namespace="Aspose.Words" %>
<% 
    Response.setContentType("application/msword"); 
    Model.Save(Response.OutputStream, SaveFormat.WordML); %>
</asp:Content>
If you know a simpler way, please post in comments.

1 comment:

Mitch Fincher said...

OK, yep, there's a much easier way. (Sorry about the earlier post, I just get giddy when I can make a new technology just work).
Here's the easier way which gets rid of the View. Thanks Rob James for your comment.


public FileStreamResult MergeAndDownload(Choice choice)
{
//get the aspose stream
var memoryStream = Processor.UpdateSurveyMemoryStream(choice);
var fileStreamResult = new FileStreamResult(memoryStream, "application/ms-word");
fileStreamResult.FileDownloadName = string.Format("SuggestedName.doc",
return fileStreamResult;
}