What's the best way to serve up multiple binary files from a single WebApi method?

前端 未结 3 974
清酒与你
清酒与你 2020-12-05 19:38

I have an ASP.NET MVC 4 Web Api controller method that gets passed a list of file IDs and returns thumbnail images for those files.

So, the client might pass in a li

相关标签:
3条回答
  • 2020-12-05 19:50

    You could create a compressed file (e.g. a ZIP file) out of all the thumbnails and send that back.

    Then the caller just has to unzip it their end - sending a single file containing multiple files is going to be far more acceptable then sending multiple files in a single stream.

    Disadvantage is you're less likely to be able to take advantage of caching (depending on your usage patterns of course).

    0 讨论(0)
  • 2020-12-05 19:54

    OK, here's a snippet of code that seems to work, using the MultipartContent that KiranChalla referred to. (This is just a dummy sample that shows how to return two files of different types, in conjunction with a JSON-encoded "object" (which in this case is just a list of integer IDs).

    public HttpResponseMessage Get()
    {
        var content = new MultipartContent();
        var ids = new List<int>() { 1, 2 };
    
        var objectContent = new ObjectContent<List<int>>(ids, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
        content.Add(objectContent);
    
        var file1Content = new StreamContent(new FileStream(@"c:\temp\desert.jpg", FileMode.Open));
        file1Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
        content.Add(file1Content);
    
        var file2Content = new StreamContent(new FileStream(@"c:\temp\test.txt", FileMode.Open));
        file2Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain");
        content.Add(file2Content);
    
        var response = new HttpResponseMessage();
        response.Content = content;
        return response;
    }
    
    0 讨论(0)
  • 2020-12-05 20:03

    One challenge I see is that based on the number of images being sent back the caller has to adjust their timeout value. If this was for a book store, there could be a lot of images sent back.

    What if you only sent back the urls for each image and leave it up to the caller to get the actual image? It would mean a little more traffic with multiple calls but the caller would get back information sooner than later and then get the images based on the caller's requirement.

    I could be wrong, but I thought the idea behind rest was to identify each resource versus bundling a bunch of images and calling that a resource. Just a thought...

    0 讨论(0)
提交回复
热议问题