Welcome to MSDN Blogs Sign in | Join | Help

Pranab Paul's Blog - Development Tips on SharePoint, Office and Web

------------------------------------------Web Parts, Workflow, InfoPath Form Services, Features, Site Definition, Event Receivers, Excel Services, Business Data Catalog (BDC), Search

News

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

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.

Posted: Monday, July 02, 2007 7:12 PM by pranab

Comments

Christine said:

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?

# September 3, 2007 10:50 PM

tom said:

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!

# October 1, 2007 2:10 PM

pranab said:

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();

}

# October 1, 2007 4:48 PM

tom said:

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!

# October 18, 2007 3:58 PM

tom said:

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);

..........

# October 23, 2007 11:08 AM

tom said:

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!

# October 25, 2007 11:53 AM

Priyanga Darshana said:

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?

# November 11, 2007 11:47 PM

Balaji Santosh said:

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.

# February 21, 2008 10:03 PM

Pepe said:

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

# June 4, 2008 1:40 PM

Andy said:

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

# June 24, 2008 3:14 PM

Ipsita said:

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.

# July 17, 2008 7:13 AM

Yash said:

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 ?

# August 4, 2008 4:26 PM

Suzanne said:

This is great! Thanks for posting.

# August 25, 2008 6:04 PM

Robert Chyra said:

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

# September 9, 2008 6:27 AM

Rahul said:

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?

# September 11, 2008 3:33 AM

Hannah said:

Hi Pranab

I am getting the error "The Web application at http://mossdev01/Record%20Update%20Attachments/usability.doc 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.".

My SiteURL is set as above to:

string SiteURL = "http://mossdev01/Record%20Update%20Attachments/" + fileName;

The form is successfully submitted to the form library but the attachment fails on the line:

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

Have you come accross this before?

Cheers

Hannah

# September 25, 2008 12:45 PM

Hannah said:

Hi

I have managed to get this working now - i was developing on one server and running it on another - have now installed InfoPath on the same server as the form library and it it running ok.

Have aded in Tom's update looping through to add multiple attachments.

One question - has anyone added in functionality to enable exisiting documents in the doc library to be overwritten? Not sure if this should be a code thing or a setting in the form or even the doc library??

Many thanks

Hannah

# September 26, 2008 7:20 AM

Nitin said:

This is a typical workflow process where review is happening between two persons (Person "A" and Person "B").A Task has assigned to Person "A" for Review and after this Review, there is a set of code to be executed. Hence forth Task for Person "B" would be created. In this Scenario, when error occurs (while executing the set of code), how can I Reassign the Task to the Same Person.

Scenario 1:

Now in a typical scenario, this happened that, when the set of code (Lets say, adding the user details to a Database and database connection fails) is executed and some error had occurred. Prior to that, the Workflow completed the Task for Person "A" and created the Task for Person "B".

In other words, when the Person A’s Task is Erroneous, we should Reassign the Task to the same person rather creating Task for Person "B".

But the WWF Framework for Sequential Workflow is designed in such a way that it is forward only and the desired scenario is to sustain the status of Task till next level unless it is error free. I am really looking for some Activities using that I can reassign the Task to the same person when there is Review Error.

 Or

Is there any typical activity to handle the flow of Custom workflow to previous level, case when error occurs?

Also looking for suggestion on the Error Handling part for WWF.

# October 23, 2008 6:33 AM

Nitin said:

Infopath form contains a Contact Selector Activex Control referring to Manager Name. I need to make this field as mandatory. When it comes to default controls (Like TextBox, CheckBox, RadioButton etc.), using Data Validation I can make the field Mandatory,. But this Contact Selector control does not support Data Validation.

The other way around I tried with VSTA coding. I set a value of contact Selector to one more textbox and used Data Validation to that Textbox. But this Scenario is working fine till the InfoPath form is Browser rendered. When I make the form rendered as browser, this code is not working.

# October 23, 2008 6:34 AM

ashishkanoongo said:

Hello Pranab

I am working in different sceherio. My infopath library is email enabled. I want to check whenever any email received for that form library. I want to delete attachment and add another xml file which I generated using an xslt file and transform. I just tested with itemadded event and update title field as below, but how do I delete attchment. I want to make sure it should delete only those attachment whenever item received thru email. Please advise

public class EmailReceiver : SPItemEventReceiver    

   {  

       public override void ItemAdded(SPItemEventProperties properties)  

       {  

           //SPListItem item = null;  

           try  

           {  

               this.DisableEventFiring();  

               properties.ListItem["Title"] = "Tested by AK Item";  

               properties.ListItem.Update();  

               this.EnableEventFiring();  

           }  

           catch (Exception ex)  

           {  

               //item["Title"] = ex.ToString();  

               EventLog.WriteEntry("Error", ex.ToString());  

           }  

       }  

# January 2, 2009 3:36 PM

helen said:

Hi,The code shows me some error message

System.IndexOutOfRangeException

Index was outside the bounds of the array.

  at InfoPathTest.FormCode.CTRL3_5_Clicked(Object sender, ClickedEventArgs e)

  at Microsoft.Office.InfoPath.Internal.ButtonEventHost.OnButtonClick(DocActionEvent pEvent)

  at Microsoft.Office.Interop.InfoPath.SemiTrust._ButtonEventSink_SinkHelper.OnClick(DocActionEvent pEvent)

why its so please help me

# January 7, 2009 11:21 PM

Harit said:

Hi

I executed the code i get the following error can u please say y that happens

Invalid character in a Base-64 string.

# January 9, 2009 1:40 AM

Sunil said:

I have an infopath form that is web enabled. I have a file attachment control on my form. Is there a limit on the file size that can be uploaded and if so, are there any workarounds ? I know that sharepoint 2007 itself has a 50MB default file size limit, but, that can be changed by going into CA. Anything similar in infopath ?

thanks for your help.

Sunil

# March 11, 2009 1:08 PM

Avijit Das said:

Hi Pranab,

I would like to know what happens with the file attachment control after we detach the attachments to a document library. The options are:

1. Keep it as it is. In this case, anyway the attachments are embedded in the Form's XML. So, the Form really does not become lightweight.

2. Replace the attachment control with hyperlink (not sure if this is possible) and then bring back if I am trying to edit the Form.

Looking ahead for your response.

Regards,

Avi

# June 5, 2009 12:00 PM

Selva said:

I had created the VSTA code what you are mentioned above but

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

Here i am getting error like object reference

pls let me know

Thanks

selva

# July 2, 2009 6:21 AM

uday patel said:

Hi Pranab,

Thank you very much in advance.

Its really urgent for us so any help greatly appreciated.

Question is : How to delete the Infopath Form attachments Once its been copied over to another document library? Can you please provide me any source code as i have tried deleteself() and executeaction method but nothing seems tobe worked on my code.

Thanks

Uday Patel

# September 25, 2009 4:53 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker