Help manually attaching a image to resource


Well-known member
Hi folks,

In an add-on I'm working on I have to manually attach a file to a resource.
I had it working by manually copying to the file to the data directory, and inserting the various bits into the xf_attachment and xf_attachment_data tables but thought that was a bit messy.

So, I picked apart the importer code and now have this:
        $temporaryImageDirectory = XenForo_Helper_File::getTempDir();
        $basename = basename($sourceFile);
// make sure basename fits 100 character limit
        if (strlen($basename) > 100)
            $strlen = strlen($basename);
            $pos_start = $strlen - 100;
            $basename = substr($basename,$pos_start);
        $tempFullPath = tempnam(XenForo_Helper_File::getTempDir(), 'xf'). "." . $ext;

//doing other stuff here, code removed        
//here a valid image file exists and can be opened in any image viewer. 

        $filex = new XenForo_Upload("preview1.jpg", $tempFullPath);
        $uploadDate = time();
        $att = $this->getModelFromCache('XenForo_Model_Attachment');
        $dataExtra = array('upload_date' => $uploadDate, 'attach_count' => 1);
        $data_id = $att->insertUploadedAttachmentData($filex, $currentUserId, $dataExtra);
        $dw = XenForo_DataWriter::create('XenForo_DataWriter_Attachment');
        $dw->setImportMode(true); //not yet sure if I should have this in or not.

            'data_id' => $data_id,
            'content_type' => 'resource_update',
            'content_id' => $resourceId,
            'attach_date' => $uploadDate,
            'unassociated' => 0

        $newAttachmentId = $dw->get('attachment_id');
        print "newAttachmentId:" . $newAttachmentId;

I get back data_id and newAttachmentId but they don't exist in the DB.
Is there an uncommited transaction I need to commit?

is there a "global" save I need to call?



Well-known member
disregard - it looks like it does show up in the DB if the page loads to completion. As part of debug I print and die. That caused the red herring :(

But - on the page now all I see is :
View attachment 47477

if I click on it I can view the image. But it does not embed into the message even though I updated the message with View attachment 47477