0

So I'm receiving documents via a REST api GET request that returns JSON containing the files as base64 encoded data along with metadata about the file such as filename and description.

Here is an example of the JSON being returned (real base64 data replaced with "BASE64 ENCODED FILE" for readability):

"documents":[  
    {  
        "name":"Job Description.doc",
        "description":"Job Description",
        "data":"BASE64 ENCODED FILE"
    },
    {  
        "name":"Person Description.doc",
        "description":"Person Description",
        "data":"BASE64 ENCODED FILE"
    }
]

I know I can json_decode() the data, then do:

file_put_contents('/path/to/file/'.base64_decode($documents->data));

The problem with this is that the file is then permanently stored (which is not acceptable in this case). I would like to know if there is any way to offer the file for download without storing it as a file anywhere. Perhaps in a similar way to how a base64 encoded image can be used as the source for an image tag.

What are your thoughts? Can this be done?

Marc
  • 746
  • 1
  • 12
  • 28

1 Answers1

1

It looks that you're using php on your server.

According to what I understand :

  1. Your visitor client/browser makes a request to your server,
  2. Your server runs some php code and initiates a REST request to another server,
  3. Your server received json data, in response to your REST request,
  4. Your php code sends the response to your visitor client/browser (or finishes the response),
  5. Optionally, your php code does some stuff after sending the response.

The problem is, that by the end of the process, you must either have saved the document content somewhere or have it transmitted to your visitor client/browser. Else it's lost for your server (and, except in some special cases, I'd rather avoid doing multiple times the REST HTTP requests that deliver files content).

Transmitting all files to your visitor in the response, before the data is lost, is something possible. A way to do it is the following :

  1. Your visitor click on a link (initiating the REST request on your server...)
  2. As a response, your visitor receives ONE download (for example a zip file, or a tar.bz2...).

Another way that seems feasible is to send HTML content to your browser that contains all files content, encoded. And then client-side code would do the remaining of the job. I'm not sure if I'd do it this way, but you may have a look at https://stackoverflow.com/a/3916267/1106814

However, unless I'd have special conditions, I'd rather "save" the file content, temporarily on the server. There are multiple ways to have an acceptable solution :

  • Use a cron mechanism to purge expired content
  • Use a tmpfs (or similar) solution to increase chances that your temporary file is not even written to a physical disk
  • And probably many other ways...

I hope to have provided useful thoughts.

Community
  • 1
  • 1
dotpush
  • 428
  • 3
  • 14