[英]Download a file with ServiceStack HttpResult: how to specify a file name for downloaded content?
[英]Download file (html content) with ServiceStack
我将服务堆栈用于一个简单的 Web 应用程序。
在这个应用程序中,我需要将一些内容“导出”到 Excel。所以这是我采取的方法:
GET
方法,我读取文件并使用ContentType:"application/vnd.ms-excel"
我在其他时候使用了这种没有 Service Stack 的方法,效果很好.. XLS
文件有正确的内容和一些颜色。
现在,当我使用GET
方法(即使用浏览器访问 url)获取文件时,文件内容是错误的。
ServiceStack 允许下载一些格式:html、csv、jsv、json、xml。
html 格式显示了一个默认的报告页面,唯一有效的格式是 jsv。
我的问题是:如何下载纯 html 文件之类的文件?
一些代码:
public class ExcelService : RestServiceBase<Excel>
{
public override object OnGet (Excel request)
{
string file = request.nombre;
//Response.Clear();
HttpResult res = new HttpResult();
res.Headers[HttpHeaders.ContentType] = "application/vnd.ms-excel";
res.Headers[HttpHeaders.ContentDisposition] = "attachment; filename="+file+".xls";
string archivo = System.IO.File.ReadAllText("tmp/"+file+".html");
res.Response = archivo;
return res;
}
}
提前致谢
ServiceStack 中的 HttpResult 构造函数作为支持文件下载的重载,例如:
return new HttpResult(new FileInfo("tmp/"+file+".html"),
asAttachment: true,
contentType: "application/vnd.ms-excel");
这将设置文件下载所需的ContentDisposition
HTTP 标头。
为了对 HttpOutput 进行更细粒度的控制,您还可以创建自己的 Result 类。 以下是从ServiceStack question 中的自定义响应中下载 Excel 电子表格的示例:
public class ExcelFileResult : IHasOptions, IStreamWriterAsync
{
private readonly Stream _responseStream;
public IDictionary<string, string> Options { get; private set; }
public ExcelFileResult(Stream responseStream)
{
_responseStream = responseStream;
Options = new Dictionary<string, string> {
{"Content-Type", "application/octet-stream"},
{"Content-Disposition", ""attachment; filename=\"report.xls\";"}
};
}
public async Task WriteToAsync(Stream responseStream, CancellationToken token = default)
{
if (_responseStream == null)
return;
await _responseStream.CopyToAsync(responseStream, token);
await responseStream.FlushAsync(token);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.