簡體   English   中英

使用 ServiceStack 下載文件(html 內容)

[英]Download file (html content) with ServiceStack

我將服務堆棧用於一個簡單的 Web 應用程序。

在這個應用程序中,我需要將一些內容“導出”到 Excel。所以這是我采取的方法:

  1. 我使用 jQuery 獲取表格的 HTML 內容,並獲取表格的 HTML 內容,然后發送到服務。
  2. 服務將內容寫入文件(帶有一些 CSS)
  3. 使用相同的服務,但使用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 標頭。

創建自己的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM