7

I'm building a file-manipulation API in Rails, and I need to be able to access it via a separate gem. The API uses Carrierwave, and that piece works with no trouble. What I don't understand how to do is to take an arbitrary file and deliver it to the API from the gem interface.

Carrierwave takes its files as either the results of File.open('foo.jpg') or as a POST from a file field. I'm really not sure what either is doing, though, to serialize the file and send it along.

How do I take the contents of a file and turn that into something I can pass around and post via JSON?

Mark Tabler
  • 1,421
  • 10
  • 16

1 Answers1

4

When an HTML form POSTs a file, what actually happens is a special part of HTTP called a multipart request. Effectively, the file gets "attached" to the request.

The question will be answered by what library you are using to POST the JSON to your api. Attaching a file to a request should be fairly commonplace but not all libraries may support it.

This stack overflow article seems to give some good indications of how to do it.

Community
  • 1
  • 1
Daniel Evans
  • 6,788
  • 1
  • 31
  • 39
  • This is a great way to accomplish the things I was trying to accomplish. It sounds like the original question starts with a bad premise - a file wouldn't be serialized to a JSON object at all, but rides in a completely different part of the protocol. In any event, this library gets me off to a great start, and if I get to wondering how it does what it does I can always hit the source code of that. Thanks! – Mark Tabler Sep 27 '12 at 06:28
  • Exactly. Notably, you CAN embed a file in the JSON using base64 encoding or some other ASCII encoding, however I wouldn't recommend that path unless you really need it. – Daniel Evans Sep 27 '12 at 16:32