How can I do to insert an image into a database?

I have not seen a MODx example, but there can be a fair amount of complexity to accomplish what you want.

Idea for MODX:
The “content” field on a resource is a MEDIUMTEXT field which should store up to 16MB of data or ~16Million characters. You could create a content type for images and simply store the base 64 Encoded data in the Content field.

  • You would need an “Image” template with a snippet to decode the content from Base64.
  • You would need to carefully restrict the image sizes so that they don’t exceed the field length limits
  • Make sure that the snippet is using the uncached flag

Other example structure:
One complex/robust solution I have seen in a different commercial product does the following:

  1. Transfer the image to the server
  2. Base64 encode the image
  3. Break the encoded string into blocks of a certain size (not sure the exact size they use)
  4. Store an attachment record that has the metadata around the file/image including things like MIME Type, file size, etc.
  5. Store the encoded blocks as child records related to the parent “attachment”
  6. The uploaded file is discarded after successful save

Then to render the image back to the client you would need a snippet or endpoint. In this particular solution, you go to a /attachments.do?sys_id=<id_of_parent_attachment>.

That processor has to reverse and put together all the data.

  1. Query for all the child data blocks
  2. Concatenate back to a single Base64 string
  3. Decode it back to the source type
  4. Apply filename and needed details from the metadata attachment record
  5. Trigger the download back to the client

As you can see there is a fair amount of overhead. You could definitely do this in MODX, but you may need a custom table.

I believe one of the reasons they break the attachment into blocks is file size issues and database field types. Base64 encoding the file also increases the total data storage requirements since the string encoding data is larger than the file.

There are benefits for the trade-offs, but you’d really have to have a strong reason I think. One of the biggest benefits can be security of access to the file data potentially on a shared application or similar. You can apply an application level security model that enforces more granularity than with the file structure (I think, in general).

Anyway, hope that helps.

-Jared