我正在使用Service Stack来实现一个简单的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;
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢
myt*_*thz 11
ServiceStack中的HttpResult构造函数作为支持文件下载的重载,例如:
return new HttpResult(new FileInfo("tmp/"+file+".html"),
asAttachment: true,
contentType: "application/vnd.ms-excel");
Run Code Online (Sandbox Code Playgroud)
这将设置ContentDisposition文件下载所需的HTTP头.
为了更好地控制HttpOutput,您还可以创建自己的Result类.以下是从ServiceStack问题中的自定义响应中下载Excel电子表格的示例:
public class ExcelFileResult : IHasOptions, IStreamWriter
{
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 void WriteTo(Stream responseStream)
{
if (_responseStream == null)
return;
_responseStream.WriteTo(responseStream);
responseStream.Flush();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4280 次 |
| 最近记录: |