Attaching an image to a node - version 7

Eoin Maguire asked on June 17, 2014 12:18

I’m migrating code from version 5 to version 7 and am having trouble with uploading an image. The page allows a user to choose an image and then when the form is submitted it uploads this image into a sub folder as a new node.

The code I have is as follows:

public static bool AddImageToNode(UserInfo user, int nodeId, string newNodeName, System.Web.HttpPostedFile postedFile) { bool fileAdded = false;

    TreeProvider tree = new TreeProvider(user);
    CMS.DocumentEngine.TreeNode fundraisingPageNode = DocumentHelper.GetDocument(nodeId, defaultCulture, tree);

    if (fundraisingPageNode != null)
    {
        CMS.DocumentEngine.TreeNode imagesFolderNode = tree.SelectSingleNode(siteName, fundraisingPageNode.NodeAliasPath + "/Images", defaultCulture, true, "CMS.Folder", false);

        if (imagesFolderNode != null)
        {
            //add file document
            CMS.DocumentEngine.TreeNode fileNode = CMS.DocumentEngine.TreeNode.New("CMS.File", tree);
            fileNode.NodeAlias = newNodeName;
            fileNode.NodeName = newNodeName;
            fileNode.SetValue("FileName", postedFile.FileName);
            fileNode.DocumentCulture = defaultCulture;

            fileNode.Insert(imagesFolderNode.NodeID);

            if (fileNode.NodeID > 0)
            {
                //add attachment
                AttachmentManager am = new AttachmentManager();


                // Create the attachment and resize it
                Guid attachmentGuid = Guid.NewGuid();
                AttachmentInfo ai = new AttachmentInfo(postedFile, fileNode.DocumentID, attachmentGuid);

                System.IO.MemoryStream msIn = new System.IO.MemoryStream(ai.AttachmentBinary);
                System.IO.MemoryStream msOut = new System.IO.MemoryStream(ai.AttachmentBinary);
                System.Drawing.Image img = System.Drawing.Image.FromStream(msIn);

                img.Save(msOut, System.Drawing.Imaging.ImageFormat.Jpeg);
                ai.AttachmentBinary = msOut.ToArray();
                am.SetAttachmentInfo(ai);

                // Set the attachment reference
                fileNode.SetValue("FileAttachment", attachmentGuid);
                fileNode.Update();
            }
        }
    }

I end up with what looks like the image but there doesn’t appear to be any file attached so nothing displays. Is there something I’m not doing right?

Recent Answers


Brenden Kehren answered on June 18, 2014 09:13

So it would be a File doc type that you are uploading or an attachment to a document? You might want to check out the /CMSApiExamples on your local install. It has a lot of code examples on "how to".

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.