How to consume a file with a ServiceStack client

后端 未结 4 656
盖世英雄少女心
盖世英雄少女心 2021-02-01 23:34

I am trying to use ServiceStack to return a file to a ServiceStack client in a RESTful manner.

I have read other questions on SO (here and here) which advise using HttpR

4条回答
  •  梦谈多话
    2021-02-02 00:12

    I had a similar requirement which also required me to track progress of the streaming file download. I did it roughly like this:

    server-side:

    service:

    public object Get(FooRequest request)
    {
        var stream = ...//some Stream
        return new StreamedResult(stream);
    }
    

    StreamedResult class:

    public class StreamedResult : IHasOptions, IStreamWriter
    {
        public IDictionary Options { get; private set; }
        Stream _responseStream;
    
        public StreamedResult(Stream responseStream)
        {
            _responseStream = responseStream;
    
            long length = -1;
            try { length = _responseStream.Length; }
            catch (NotSupportedException) { }
    
            Options = new Dictionary
            {
                {"Content-Type", "application/octet-stream"},
                { "X-Api-Length", length.ToString() }
            };
        }
    
        public void WriteTo(Stream responseStream)
        {
            if (_responseStream == null)
                return;
    
            using (_responseStream)
            {
                _responseStream.WriteTo(responseStream);
                responseStream.Flush();
            }
        }
    }
    

    client-side:

    string path = Path.GetTempFileName();//in reality, wrap this in try... so as not to leave hanging tmp files
    var response = client.Get("/foo/bar");
    
    long length;
    if (!long.TryParse(response.GetResponseHeader("X-Api-Length"), out length))
        length = -1;
    
    using (var fs = System.IO.File.OpenWrite(path))
        fs.CopyFrom(response.GetResponseStream(), new CopyFromArguments(new ProgressChange((x, y) => { Console.WriteLine(">> {0} {1}".Fmt(x, y)); }), TimeSpan.FromMilliseconds(100), length));
    

    The "CopyFrom" extension method was borrowed directly from the source code file "StreamHelper.cs" in this project here: Copy a Stream with Progress Reporting (Kudos to Henning Dieterichs)

    And kudos to mythz and any contributor to ServiceStack. Great project!

提交回复
热议问题