Freigeben über


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 = "https://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.

Comments

  • Anonymous
    September 03, 2007
    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?

  • Anonymous
    October 01, 2007
    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!

  • Anonymous
    October 01, 2007
    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(); }

  • Anonymous
    October 18, 2007
    The comment has been removed

  • Anonymous
    October 23, 2007
    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); ..........

  • Anonymous
    October 25, 2007
    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!

  • Anonymous
    November 11, 2007
    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?

  • Anonymous
    February 21, 2008
    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.

  • Anonymous
    June 04, 2008
    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

  • Anonymous
    June 24, 2008
    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

  • Anonymous
    July 16, 2008
    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.

  • Anonymous
    August 04, 2008
    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 ?

  • Anonymous
    August 25, 2008
    This is great! Thanks for posting.

  • Anonymous
    September 08, 2008
    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

  • Anonymous
    September 10, 2008
    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?

  • Anonymous
    September 25, 2008
    The comment has been removed

  • Anonymous
    September 25, 2008
    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

  • Anonymous
    October 22, 2008
    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.

  • Anonymous
    October 22, 2008
    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.

  • Anonymous
    January 02, 2009
    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());              }          }  

  • Anonymous
    January 07, 2009
    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

  • Anonymous
    January 08, 2009
    The comment has been removed

  • Anonymous
    March 11, 2009
    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

  • Anonymous
    June 05, 2009
    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
  • Anonymous
    July 01, 2009
    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

  • Anonymous
    September 25, 2009
    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

  • Anonymous
    August 17, 2010
    Thank you - from 2007 to 2010 - this is very helpful!

  • Anonymous
    August 24, 2010
    If you find this solution isn't as flexible as you need, try a web handler solution, you can download a demo here: http://blog.mgallen.com/?p=350 It will work with any InfoPath form and loop through all attachments, no matter where they are in the form structure.

  • Anonymous
    March 15, 2011
    Hi Pranab, I'm getting the following error on running the code... The Web application at http://punitp120806d:11100/sites/POC/Documents/Test.txt 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. Though the URL is perfectly valid and i've digitally signed and given full trust. Ive also made it administrator approved template as i'm site collection admin as well as farm admin.... Please help :(

  • Anonymous
    September 22, 2011
    i know i'm way late...but i was searching for a way to have files that users attach to the infopath form be included in the email that is sent via a Submit button i have on the form.  when it is clicked the completed form is emailed to me.  but i don't get the file they attached.  i have to open the form in sharepoint in ordet to download the attachment.