How to Add the Attachment from an InfoPath 2007 Form to a SharePoint 2007 (MOSS/WSS) Document Library

How to Add the Attachment from an InfoPath 2007 Form to a SharePoint 2007 (MOSS/WSS) Document Library

  • Comments 30

I have an InfoPath 2007 Form where I have a Text Box, a File Attachment field and a Button. I changed the property of the button to make it a Submit button. My target is to post the Form’s instance into a Form Library. And then put the file which I have attached through the File Attachment field to a separate Document Library.

In the Button Properties Pop-up, I have selected “Rules and Custom Code” as Action. Added a Rule to post the Form Instance in a SharePoint Form Library. I have used VSTA to add the necessary code to the Form Template. You can find it in Tools>Programming Menu. You can use VSTO also. I added a reference of “Windows SharePoint Services” and used the following code:

using Microsoft.Office.InfoPath;

using System;

using System.Xml;

using System.Xml.XPath;

using Microsoft.SharePoint;

using System.IO;

 

namespace Template1

{

    public partial class FormCode

    {

        public void InternalStartup()

        {

 

            ((ButtonEvent)EventManager.ControlEvents["Submit"]).Clicked += new ClickedEventHandler(Submit_Clicked);

        }

 

        public void Submit_Clicked(object sender, ClickedEventArgs e)

        {

            XPathNavigator docXN = this.CreateNavigator();

            XPathNavigator opnXN = docXN.SelectSingleNode("/my:myFields/my:fileup", this.NamespaceManager);

            byte[] attachmentNodeBytes = Convert.FromBase64String(opnXN.ToString());

 

            // Position 20 contains a DWORD indicating the length of the

            // filename buffer. The filename is stored as Unicode so the

            // length is multiplied by 2.

            int fnLength = attachmentNodeBytes[20] * 2;

            byte[] fnBytes = new byte[fnLength];

 

            // The actual filename starts at position 24 . . .

            for (int i = 0; i < fnBytes.Length; i++)

            {

                fnBytes[i] = attachmentNodeBytes[24 + i];

            }

 

            // Convert the filename bytes to a string. The string

            // terminates with \0 so the actual filename is the

            // original filename minus the last character !

            char[] charFileName = System.Text.UnicodeEncoding.Unicode.GetChars(fnBytes);

            string fileName = new string(charFileName);

            fileName = fileName.Substring(0, fileName.Length - 1);

 

            // The file is located after the header, which is 24 bytes long

            // plus the length of the filename.

            byte[] fileContents = new byte[attachmentNodeBytes.Length - (24 + fnLength)];

 

            for (int i = 0; i < fileContents.Length; ++i)

            {

                fileContents[i] = attachmentNodeBytes[24 + fnLength + i];

            }

            string SiteURL = "http://myserver/sites/newsite/newdoclib/" + fileName;

            SPWeb site = new SPSite(SiteURL).OpenWeb();

            site.Files.Add(SiteURL, fileContents);

 

        }

 

    }

}

Remember, if you use coding with your InfoPath Form, you need to make it Full Trust, have to Sign it Digitally and while publishing it in a SharePoint Site it should be approved by an Administrator.

Leave a Comment
  • Please add 8 and 1 and type the answer here:
  • Post
  • Hi Pranab. Is this the only way to add the attachment file from Infopath 2007 to MOSS 2007? Any other alternatives? By the way, are we able to detach the attachment file from InfoPath 2007 and then add it into the MOSS 2007 library document?

  • Hi Pranab,

    This is a great! Now, I can use your code to detach a file to SharePoint.  How would you handle zero to many attachements to be detached (Looping)?

    Thanks a lot!

  • In this part of Code (XPathNavigator opnXN = docXN.SelectSingleNode("/my:myFields/my:fileup", this.NamespaceManager);) you are paasing the xpath of the file attachment field as a parameter of string type.

    Now if you have 5 file attachment fields (fileup0 - fileup4) then use something like:

    for (int i = 0; i < 5; i++)

    {

      string s = "/my:myFields/my:fileup";

      s += i.ToString();

    }

  • Hi Pranab,

    Thank you for the suggestion.

    But I was thinking along the line of using repeating section for the file attachment.

    I’ll not know how many files have been attached in advance.  

    My code will loop through to figure out zero to many files and detach it to differnt SharePoint sites depend on the content type of file.

    Thanks a lot!

  • Zero to many attachements to detach:

    Here is looping code if anyone interested.....

    XPathNavigator docXN = this.CreateNavigator();

    XPathNavigator opnXN = docXN.SelectSingleNode("/my:myFields/my:file", this.NamespaceManager);

    XPathNodeIterator xi = opnXN.Select("/my:myFields/my:file", NamespaceManager);

    while (xi.MoveNext())

    {

     string s = xi.Current.Value;

     byte[] attachmentNodeBytes = Convert.FromBase64String(s);

    ..........

  • Hi Pranab,

    Do you know how to delete attachement file with code?

    Once I copied attachements to Sharepoint, I want to delete from the InfoPath form.

    I've been trying with ExecuteAction(xFileAttachementRemove, string)method, but couldn't make it work.

    Thanks a lot!

  • Showing doument data in TaskForms

    Hi,

    This was an excellent demo.

    I have a question. Following is the scenario.

    I have developed a statemachine workflow for our company expense approval and it had being associated with a infopath form Library. Now users will going to upload Infopath forms (tempate is already set up for libaray). So, I want to extract some details from those uploading files to my Infopath Task forms to display it. (e.g. User1 enter the expense figure in infopath file and upload to form libaray assigning it to user2. When user2 view task he should be able to see the those expense figures in his Infopath Task form as well)

    How to do it?

  • Hi Pranab,

             This is gr8. I had a problem with attachments in infopath 2007 when i use in sharepoint 2007. when i upload the document in any format, its working well. When i download the same document, it is being converted to .aspx format(if .net is installed), otherwise .zip format. can you help me in this regard.

  • Hey,

    I still have the base64 error when I am publishing the InfoPath form to my SharePoint Server. I made it full trust and everything but still doesnt work.

    I would appreaciate any help!

    Pepe

  • How can I store the file with its name based on a form FIELD's value. I have a text Field called "FinalFile", so the file name should be value of "FinalFile" field, not the actual name of the attachment.

    ex:

    Actual name of attachment... good.doc

    Value in FinalFile..... bad.doc

    So it should be stored as bad.doc to the doc library.

    Thanks

  • Hi Pranab..whenever i attach a file in infopath and save the form in a form library in share point and then see the xml of that form...i get the attached document as binaries...can you suggest some way to convert the binaries back to its original format.

  • Hi Pranab,

    Nice article.

    But I have a problem while retrieving the file attachment. I am submitting the file attachment as byte[] in SQL Server 2005 table. How can I assign the same byte[] in that file attachment field ?

  • This is great! Thanks for posting.

  • Hi,

    I have problem with browser-enabled InfoPath form and InfoPath Forms Services - every time I loaded attachments do my form it is refresh to the client's browser (if I attach 6 MB file do forms, I see it is loading to server and finally data is loading back to the client's browser)

    And the worst: if I click button SAVE (standard button generated with InfoPath Forms Services) and write the name of my form and click OK, everything happens again (data is loading back to the client's browser)

    What should I do to prevent loading back data from server to client's browser??

    Regards,

    Robert

  • Hi Pranab,

    Actually, Iam getting error "URL could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application."

    Any Idea?

Page 1 of 2 (30 items) 12