Hello, I'm working on a project that requires the ability to let a user download a pdf from a static location on the server. I'm reading the instructions from this website, it's an old post and I notice they specify in an update that Microsoft's MVC framework has long since included and Action Result that allows the same functionality they discuss thus rendering it obsolete, I've looked a bit online but haven't been able to find any resources that discuss this built-in functionality. If anyone has any links or other information that discuss this it would be very helpful. Thanks.
+1
A:
You can use the FileResult
instead of ActionResult
to return file stream in the response. For an example, look at Can an ASP.Net MVC controller return an Image? question here on SO.
Franci Penov
2010-05-06 16:57:47
+1
A:
public ActionResult Show(int id) {
Attachment attachment = attachmentRepository.Get(id);
return new DocumentResult { BinaryData = attachment.BinaryData,
FileName = attachment.FileName };
}
Which uses this custom class, probably similar to FileResult :
public class DocumentResult : ActionResult {
public DocumentResult() { }
public byte[] BinaryData { get; set; }
public string FileName { get; set; }
public string FileContentType { get; set; }
public override void ExecuteResult(ControllerContext context) {
WriteFile(BinaryData, FileName, FileContentType);
}
/// <summary>
/// Setting the content type is necessary even if it is NULL. Otherwise, the browser treats the file
/// as an HTML document.
/// </summary>
/// <param name="content"></param>
/// <param name="filename"></param>
/// <param name="fileContentType"></param>
private static void WriteFile(byte[] content, string filename, string fileContentType) {
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.ContentType = fileContentType;
context.Response.AddHeader("content-disposition", "attachment; filename=\"" + filename + "\"");
context.Response.OutputStream.Write(content, 0, content.Length);
context.Response.End();
}
}
Jason Watts
2010-05-06 18:00:44