Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Image as stream or byte array using OpenRasta

Tags:

rest

openrasta

Would anyone be able to give me a quick pointer as to how I can get an OpenRasta handler that returns a byte array. To be exposed in the ResourceSpace without it being a JSON or XML object. i.e. I don't want it transcoded, I just want to be able to set the media type to "image/PNG" or similar.

Using ASP.Net MVC I can do it using a FileContentResult by returning

File(myByteArray, "image/PNG");

I just need to know the OpenRasta equivalent.

Thanks

like image 709
Mark Dickinson Avatar asked Mar 28 '26 22:03

Mark Dickinson


2 Answers

You can just return a byte array as part of your handlerm but that will end up being served as application/octet-stream.

If you want to return files, you can simply return an implementation of IFile.

public class MyFileHandler {
  public IFile Get(int id) {
    var mybytes = new byte[];
    return new InMemoryFile(new MemoryStream(mybytes)) {
      ContentType = new MediaType("image/png");
    }
  }
}

You can also set the FileName property to return a specific filename, which will render a Content-Disposition header for you.

like image 80
SerialSeb Avatar answered Mar 31 '26 06:03

SerialSeb


I looked this up on the OpenRasta mailing list and there were a couple of related posts: http://groups.google.com/group/openrasta/browse_thread/thread/5ae2a6d653a7421e# http://groups.google.com/group/openrasta/browse_thread/thread/a631d3629b25b88a#

I have got it going with the following sample:

Configuration:

ResourceSpace.Has.ResourcesOfType<IFile>()
   .AtUri("/customer/{id}/avatar")
   .HandledBy<CustomerAvatarHandler>();

Handler:

public class CustomerAvatarHandler
{
    public object Get(int id)
    {
        const string filename = @"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg";
        return new InMemoryFile(File.OpenRead(filename));
    }
}
like image 39
Alan Christensen Avatar answered Mar 31 '26 06:03

Alan Christensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!