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?