Skip to Content

Before Introduction: This is my first blog in Webdynpro for Java. Bear with me if it is not upto the standard :).

I read many blogs & tutorial regarding attachment in webdynpro for Java when I had the same requirement. But I did not get the complete picture.

So I wanted to share my experience with you all.

 

Introduction: This blog describes how to Attach the documents from Webdynpro Application to any SAP Business transactions like MM01, IE01, VA01, FB01, WTY etc.

In order to achieve this, we are going to use Business Document Service (BDS).

 

If you have not read the Overview , I would recommend to read those before you continue this blog.

 

Before we see the steps, let us look at the result:

As I said earlier, you can attach document to (in) any Business transaction. I took an example of attaching the document into Material Master: Change Material (MM02) Transaction.
In fact by changing the RFC code, you can store the attachment data in Database table if need as per your requirement.

 

  1. Execute the webdynpro Application.
  2. Enter the Material number & choose the attachment.
  3. Now attachment got created under the business transaction with given Key.
  4. Let’s look at that attachment in SAP. As per the business object BUS1001006; the attachment can be viewed under Transaction code MM02 since we are trying to create attachment to Material Master.
  5. In MM02, mention the material number and choose the Basic view & click on “Attachment list” as shown below.
  6. Once you click on attachment, you can see the attachment list in pop-up where you can select & view the documents.
  7. Double click on document to view.
  8. Just for information: All the attachment can also be viewed in Transaction called OAOR irrespective of any Objects. Go to Tcode OAOR & enter the class name as “BUS1001006”, class type as “BO” and object key as 1000. (This is applicable only for this example.)

Let’s look at the procedure to create attachment:

Below is the Java webdynpro application which will look like once you are done with the development:

 

  1. Create the webdynpro project say Business_attachment and Applications BusinessAttachment
  2. Import the BAPI which will upload the data from webdynpro to SAP by right clicking the Model as shown below.
  3. In following screen, choose “Import Adaptive RFC Model” also enter the necessary details.
  4. Once Model is imported successfully, Add the model into webdynpro component by right clicking “Used Model” as shown below.
  5. Select the Model as shown below.
  6. Now open the data modeler & create the “Data linkage” between component controller & Model. As soon as you establish linkage it will open below screen.
  7. Select the Input node from Model as shown above & drag and drop from right to left to create and bind a new element.
  8. In following screen select the node as shown below to finish the binding.
  9. Repeat the same to establish the data linkage between component controller and View.
  10. Now create the below context node & attributes:
  11. Node “AttachmentList” cardinality is 1:n and attribute of DocContent is Type of “com.sap.ide.webdynpro.uielementdefinitions.Resource”. Material_no & DocName is type of String.
  12. The layout looks like below:
  13. Create the Event handler say “Upload File” and assign it to submit button.
  14. Here is the code for onActionUploadFile:

public void onActionUploadFile(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )

{

//@@begin onActionUploadFile(ServerEvent)

IWDMessageManager msgManager = wdComponentAPI.getMessageManager();

//wdContext.nodeAttachmentList().size();

IPrivateCreateAttachmentView.IAttachmentListElement Element= wdContext.currentAttachmentListElement();

try {

IWDResource fileResource =

wdContext.currentAttachmentListElement().getDocContent();

if (fileResource == null) {

 

} else {

String fileName;

String fileType =

fileResource

.getResourceType()

.getFileExtension()

.toUpperCase();

if(“PDF”.equals(fileType) //Just I have added some validation, you can remove this

|| “DOC”.equals(fileType)

|| “RTF”.equals(fileType)||

“XLS”.equals(fileType)) {

Element.setDocName(

Element

.getDocContent()

.getResourceName());

}

else

{

msgManager.reportWarning(“File type could not be uploaded”);

}

fileName =

wdContext.currentAttachmentListElement()

.getDocName();

InputStream fileStream = fileResource.read(false);

Zcreate_Attach_Bo_Input attach_Input =

new Zcreate_Attach_Bo_Input(WDModelScopeType.TASK_SCOPE);

attach_Input.setFile(fileName);

 

attach_Input.setObject_Key(

wdContext.currentContextElement().getMaterial_No());

int fileSize = 0;

byte[] lineContents = new byte[1022];

int numBytesRead = 0;do {

numBytesRead = fileStream.read(lineContents);

if (numBytesRead > 0) {

fileSize += numBytesRead;

Bapiconten bin = new Bapiconten();

bin.setLine(lineContents);

attach_Input.addI_File_Content(bin);

Arrays.fill(lineContents, (byte) 0);

}

} while (numBytesRead > 0);

attach_Input.execute();

msgManager.reportSuccess(“Document uploaded sucessfully.”);

}

}

 

catch (WDDynamicRFCExecuteException e) {

e.printStackTrace();

 

msgManager.reportException(

this.getClass().getName()

+ “.addAttachments:\n “

+ e.toString(),

false);

}

 

catch(Exception ex){

ex.printStackTrace();

}

//@@end

}

Finally here is the BAPI which I used to upload the file:

 

FUNCTION ZCREATE_ATTACH_BO.

*”——————————————————————–

*”*”Local Interface:

*” IMPORTING

*” VALUE(FILE) TYPE SAPB-SAPFILES

*” VALUE(OBJECT_KEY) TYPE BAPIBDS01-OBJKEY

*” TABLES

*” I_FILE_CONTENT STRUCTURE BAPICONTEN

*”——————————————————————–

DATA: LOGICAL_SYSTEM TYPE BAPIBDS01-LOG_SYSTEM,

CLASSNAME TYPE BAPIBDS01-CLASSNAME,

CLASSTYPE TYPE BAPIBDS01-CLASSTYPE.

DATA: IT_FILES TYPE TABLE OF BAPIFILES,

IT_SIGNATURE TYPE TABLE OF BAPISIGNAT,

FILES TYPE BAPIFILES,

SIGNATURE TYPE BAPISIGNAT.

 

DATA: I_TOADD TYPE TOADD,

FILENAME_ALL TYPE SAPB-SAPFILES,

FILE_PATH TYPE SAPB-SAPFILES,

FILE_PATH_MEMORY(250) TYPE C, ” path für SAP memory

FILE_PATH_LENGTH TYPE I, ” length of the file_path

FILE_CONTENT_LENGTH TYPE I, ” length of the file_CONTENT

FILE_NAME TYPE SAPB-SAPFILES,

FILE_EXTENSION TYPE TOADD-DOC_TYPE. ” file-extension.

DATA: WA_FILE_CONTENT TYPE BAPICONTEN,

STRING_CONTENT TYPE STRING,

STRING_CONTENT1 TYPE STRING.

DATA:

I_FILES TYPE TABLE OF BAPIFILES ,

I_SIGNATURE TYPE TABLE OF BAPISIGNAT ,

I_COMPONENTS TYPE TABLE OF BAPICOMPON ,

COMPONENTS TYPE BAPICOMPON ,

I_PROPERTIES TYPE TABLE OF SDOKPROPTY ,

I_PROPERTIES2 TYPE TABLE OF BAPIPROPER ,

I_PROPERTIES_DEL TYPE TABLE OF BAPIDPROPT ,

MIMETYPE TYPE TOADD-MIMETYPE,

COMPID TYPE BAPICOMPON-COMP_ID, ” compid for popup

COMPID_FLAG(1) TYPE C, ” compid can’t be changed

MODIFY_FLAG(1) TYPE C, ” document is modified

ATTRI_FLAG(1) TYPE C, ” attri can’t be changed

TITLE_FLAG(1) TYPE C, ” titel of the popup

CANCEL_FLAG(1) TYPE C, ” cancel button Yes/No

BUTTON_TEXT(10) TYPE C,

INFO_TEXT(100) TYPE C,

VERSION_NR TYPE BDN_CON-DOC_VER_NO, ” version_nr for popup

VERSION_LANGU2 TYPE T002T-SPTXT, ” language field in POPUP

VERSION_LANGU TYPE BDN_CON-LANGU,” SPRAS language field

TITLE_TEXT(100) TYPE C, ” title of the popup

DESCRIPTION TYPE BDN_CON-DESCRIPT. ” descr. for popup

FILENAME_ALL = FILE .

* — split filename — *

DATA: LENGTH TYPE I.

DATA: PATH2(1200). ” LIKE sapb-sapfiles.

DATA: L_FILE(1200),

L_DIR(1200),

L_DELIMITER TYPE C,

L_OFFSET TYPE I,

L_BYTES TYPE I,

L_DELIMITER_OFFSET TYPE I,

L_DELIMITER_BYTES TYPE I,

L_CHAR TYPE C,

L_PREVIOUS_CHAR TYPE C,

L_LAST_CHAR TYPE C.

PATH2 = FILENAME_ALL.

LENGTH = STRLEN( PATH2 ).

L_OFFSET = 0.

WHILE L_OFFSET < LENGTH.

L_LAST_CHAR = L_CHAR. “remember last character

L_BYTES = CHARLEN( PATH2+L_OFFSET ).

L_CHAR = PATH2+L_OFFSET(L_BYTES). “get current character

IF L_CHAR = ‘/’ OR L_CHAR = ‘\’ OR L_CHAR = ‘:’.

IF L_DELIMITER IS INITIAL OR L_DELIMITER = ‘:’.

“Typically we deal with absolute paths, so the first

“delimiter is best. This allows for UNIX paths with

“‘\’ in the directory or file name

L_DELIMITER = L_CHAR.

ENDIF.

IF L_CHAR = L_DELIMITER.

L_DELIMITER_OFFSET = L_OFFSET.

L_DELIMITER_BYTES = L_BYTES.

“remember character in front of delimiter:

L_PREVIOUS_CHAR = L_LAST_CHAR.

ENDIF.

ENDIF.

L_OFFSET = L_OFFSET + L_BYTES.

ENDWHILE.

IF NOT L_DELIMITER IS INITIAL.

L_OFFSET = L_DELIMITER_OFFSET + L_DELIMITER_BYTES.

L_FILE = PATH2+L_OFFSET.

IF L_PREVIOUS_CHAR = ‘:’ OR L_DELIMITER = ‘:’.

“path ends with or after drive identifer, include the delimiter

L_DIR = PATH2(L_OFFSET).

ELSEIF NOT L_DELIMITER_OFFSET IS INITIAL.

“do not include a trailing delimiter for compatibility reasons

L_DIR = PATH2(L_DELIMITER_OFFSET).

ELSE.

CLEAR L_DIR.

ENDIF.

ELSE.

L_DIR = SPACE.

L_FILE = PATH2.

ENDIF.

FILE_PATH = L_DIR.

FILE_NAME = L_FILE.

 

**——–

* — set new file_path to SAP memory — *

FILE_PATH_LENGTH = STRLEN( FILE_PATH ).

IF FILE_PATH <> SPACE AND FILE_PATH_LENGTH < 250.

FILE_PATH_MEMORY = FILE_PATH.

SET PARAMETER ID ‘OAP’ FIELD FILE_PATH_MEMORY.

ELSE.

FILE_PATH_MEMORY = SPACE.

SET PARAMETER ID ‘OAP’ FIELD FILE_PATH_MEMORY.

ENDIF.

 

* — data declaration ———————————————— *

DATA:

SINGLE_C TYPE C.

* ——————————————————————– *

CLEAR: SINGLE_C.

LENGTH = STRLEN( FILE_NAME ).

IF LENGTH > 0.

WHILE LENGTH > 0.

SINGLE_C = FILE_NAME+LENGTH(1).

IF SINGLE_C CO ‘.’.

LENGTH = LENGTH + 1.

EXIT.

ELSE.

LENGTH = LENGTH – 1.

ENDIF.

ENDWHILE.

IF LENGTH > 0.

FILE_EXTENSION = FILE_NAME+LENGTH.

ELSE.

FILE_EXTENSION = SPACE.

ENDIF.

ELSE.

FILE_EXTENSION = SPACE.

ENDIF.

IF FILE_EXTENSION <> SPACE.

SET LOCALE LANGUAGE SY-LANGU.

TRANSLATE FILE_EXTENSION TO UPPER CASE. “#EC TRANSLANG

SET LOCALE LANGUAGE SPACE.

ENDIF.

**–

* TR001++

DATA: I_TOADV TYPE TABLE OF TOADV.

DATA: WA_TOADV TYPE TOADV.

DATA: OBJECT TYPE SAEOBJART.

SELECT * FROM TOADV INTO CORRESPONDING FIELDS OF TABLE

I_TOADV WHERE STANDARD = ‘X’.

DELETE I_TOADV WHERE AR_OBJECT CS ‘BDS’ OR AR_OBJECT CS ‘ZSEST’.

 

READ TABLE I_TOADV INTO WA_TOADV WITH KEY DOC_TYPE = FILE_EXTENSION.

*

* — get name and description for the document — *

CLEAR: COMPID,

DESCRIPTION,

VERSION_NR,

MODIFY_FLAG,

COMPID_FLAG,

ATTRI_FLAG,

TITLE_FLAG.

COMPID_FLAG = ‘ ‘. ” -> compid can’t be changed

MODIFY_FLAG = ‘S’. ” -> popup in save modus

ATTRI_FLAG = ‘X’. ” -> attri’s can be changed

COMPID = FILE_NAME.

VERSION_NR = ‘00000001’.

VERSION_LANGU2 = SY-LANGU.

TITLE_FLAG = ‘1’. ” -> BDN

 

* — get the mimetype of the docuclass — *

DATA: I_DOCUMENTCLASS TYPE TOADD-DOC_TYPE.

MOVE FILE_EXTENSION TO I_DOCUMENTCLASS.

SET LOCALE LANGUAGE SY-LANGU.

TRANSLATE I_DOCUMENTCLASS TO UPPER CASE. “#EC TRANSLANG

SET LOCALE LANGUAGE SPACE.

SELECT SINGLE * FROM TOADD INTO I_TOADD WHERE

DOC_TYPE EQ I_DOCUMENTCLASS.

IF SY-SUBRC NE 0. ” nothing found -> default!

I_TOADD-DOC_TYPE = I_DOCUMENTCLASS.

I_TOADD-MIMETYPE = ‘application/x-docType’. “#EC NOTEXT

ENDIF.

 

MOVE I_TOADD-MIMETYPE TO MIMETYPE.

 

* — fill file and signature structure — *

CLEAR: I_FILES, I_SIGNATURE.

REFRESH : I_FILES, I_SIGNATURE.

DESCRIPTION = FILE_NAME.

FILES-DOC_COUNT = 1.

FILES-DIRECTORY = FILE_PATH.

FILES-FILENAME = FILE_NAME.

FILES-MIMETYPE = MIMETYPE.

APPEND FILES TO I_FILES.

* — fill components and signature structure — *

COMPONENTS-DOC_COUNT = 1.

COMPONENTS-COMP_COUNT = 1.

COMPONENTS-MIMETYPE = MIMETYPE.

COMPONENTS-COMP_ID = FILE_NAME.

APPEND COMPONENTS TO I_COMPONENTS.

SIGNATURE-DOC_COUNT = 1.

SIGNATURE-PROP_NAME = ‘BDS_DOCUMENTCLASS’.

SIGNATURE-PROP_VALUE = FILE_EXTENSION.

APPEND SIGNATURE TO I_SIGNATURE.

SIGNATURE-PROP_NAME = ‘BDS_CONTREP’.

SIGNATURE-PROP_VALUE = ‘ ‘. “#EC NOTEXT

APPEND SIGNATURE TO I_SIGNATURE.

SIGNATURE-PROP_NAME = ‘BDS_DOCUMENTTYPE’.

SIGNATURE-PROP_VALUE = WA_TOADV-AR_OBJECT. “‘ZSRVCXLS’.”TR001+

APPEND SIGNATURE TO I_SIGNATURE.

SIGNATURE-PROP_NAME = ‘DESCRIPTION’.

SIGNATURE-PROP_VALUE = DESCRIPTION.

APPEND SIGNATURE TO I_SIGNATURE.

SIGNATURE-PROP_NAME = ‘LANGUAGE’.

SIGNATURE-PROP_VALUE = VERSION_LANGU.

APPEND SIGNATURE TO I_SIGNATURE.

CALL FUNCTION ‘BDS_BUSINESSDOCUMENT_CREA_TAB’

EXPORTING

CLASSNAME = ‘BUS1001006’

CLASSTYPE = ‘BO'” classtype_select

CLIENT = SY-MANDT

OBJECT_KEY = OBJECT_KEY

BINARY_FLAG = ‘X’

TABLES

SIGNATURE = I_SIGNATURE

COMPONENTS = I_COMPONENTS

CONTENT = I_FILE_CONTENT

EXCEPTIONS

NOTHING_FOUND = 1

PARAMETER_ERROR = 2

NOT_ALLOWED = 3

ERROR_KPRO = 4

INTERNAL_ERROR = 5

NOT_AUTHORIZED = 6

OTHERS = 7.

COMMIT WORK AND WAIT.

IF SY-SUBRC <> 0.

ENDIF.

ENDFUNCTION.

 

Download the Project file here.

 

I hope this will be useful to the community.

To report this post you need to login first.

14 Comments

You must be Logged on to comment or reply to a post.

  1. Former Member
    Hi,

    Certainly GR8 work, it has become one of my favourite blogs.

    I have been able to attach the documents but the contents of the documents is not in recognizable format.
    For E.g. I passed on Binary Value   ‘0110000101100010011010000110100101110011011010000110010101101011’ (My name) but when I opened up the attachment I got ‘                       ‘. Can you please tell me where am I doing wrong.

    This testing I have done in the R/3. 

    Cheers
    Abhishek

    (0) 
      1. Former Member
        Hi

        I creating attached documents to transaction FBV2 with Business Object FIPP (Parked Customer Invoices) and I am passing a Binary and want it to come to .DOC, .XLS, .TXT or .HTM.

        The Binary is coming from Web Dynpro.

        The document is getting attached it is the contents that is the problem.

        Cheers
        Abhishek

        (0) 
          1. Former Member
            Hi,
            Just to add more clarity. This is the data that I am passing to the FM for adding attachment to MM02.

            FILE           – A2.DOC
            OBJECT_KEY     – A002(Material No.)
            I_FILE_CONTENT – 1110000101100010011010000110100101110011011010000110010101101011

            The final parameters getting into FM BDS_BUSINESSDOCUMENT_CREA_TAB.

                EXPORTING
                  classname       = ‘BUS1001006’
                  classtype       = ‘BO'” classtype_select
                  client          = sy-mandt
                  object_key      = object_key
                  binary_flag     = ‘X’

            TABLES

            1. I_SIGNATURE

            Row Doc_Count Prop_NAME           Prop_VALUE
            1     1       BDS_DOCUMENTCLASS         DOC
            2     1       BDS_CONTREP     
            3     1       BDS_DOCUMENTTYPE         BDS_ATTACH
            4     1       DESCRIPTION         A2.DOC
            5     1       LANGUAGE              E 

            The rest of the columns i.e. DOC_ID, DOC_VER_NO, DOC_VAR_ID, DOC_VAR_TG, COMP_COUNT are all blank.

            2. I_COMPONENTS

            Just one record is there : –

            DOC_COUNT       –  00000001
            COMP_COUNT      –  00000001
            COMP_ID         –  A2.DOC
            MIMETYPE        –  application/msword
            COMP_SIZE       –  000000000000

            3. I_FILE_CONTENTS

            Only one record
            LINE – 111000010110001001101000011010010111001101101000011001010110101100000000000000000000000000000000000000000000000000000000000000000000

            This really is a very very urgent thing I would be really really oblidged if you could look into this.

            Cheers
            Abhishek

            (0) 
            1. Former Member
              Hi,

              I have analyzed the problem even further. Is this Binary Conversion anyway dependent on Unicode or versions of OS or MIcrosoft or any other configurational issue because as far as Code is concerned I do not find ant differance. As I have just copied your code completely.

              Cheers
              Abhishek

              (0) 
              1. Raja Thangamani Post author
                Are you passing the Binary content manually? If so please add the text content in the file & attach. WDJ will send binary content to FM.

                Raja T

                (0) 
                1. Former Member
                  Hi Raja,

                  I’ve tried both ways, for both the result is the same. I’ve also tried to put TEXT in the ASCII Tables Parameter and it works gr8, but I need to pass the BINARY not the TEXT.
                  What else could be the problem. Do you think it is some kind of configuration Issue or Version Mismatch between the OS and Microsoft?

                  The reason I ask this is because I have just copied your whole code to R/3 and it only attaches it to the Material No. the contents are not in legible format. So I was just wondering if it is working for you why isn’t it working for me. That is why I think that it might be some configuration issue.

                  Cheers
                  Abhishek

                  (0) 
                  1. Raja Thangamani Post author
                    Abishek,

                    All you need to do is, attach the document from web & display it in SAP R/3. If you pass the binary/ASCII content manually, it may not be correct. If u feel there is an issue in version, try in some other system.

                    Raja T

                    (0) 
                    1. Former Member
                      Hi Raja,

                      Thanks 4 your help so far.

                      Here is the code that WD guy has written.

                      I have written a BAPI Z_Fi_Rfc_Submit_Form which takes the binary input of the attachment and gives to R/3.

                      IWDResource resource = wdContext.currentContextElement().getFileResource_1();

                                              if(resource!=null){

                                     String fileType = wdContext.currentContextElement().getDataFile.getFileExtension.toUppercase();

                                        if(fileType.equals(“PDF”) || fileType.equals(“DOC”)  || fileType.equals(“RTF”) || fileType.equals(“XLS”) || fileType.equals(“TXT”)) {

                                        byte[] allBytes = getBytes(resource);

                                        if(allBytes!=null){

                                              BigInteger bInt = new BigInteger(allBytes);

                                              String str = bInt.toString(16);

                                              wdContext.currentZ_Fi_Rfc_Submit_Form_InputElement().setIn_Email_Attach(str);

                                        }else{

                                              //messageMgr.reportSuccess(“1”);

                                        }}

                                  }else{

                                        //messageMgr.reportSuccess(“2”);

                                  }// End of resouce

                      wdContext.currentContextElement().setFileResource_1(null);

                                  wdContext.currentContextElement().setFileResource2(null);

                                  wdContext.currentContextElement().setFileResource3(null);

                            try{

                                       

                                   wdContext.currentZ_Fi_Rfc_Submit_Form_InputElement().modelObject().execute();

                                   wdContext.nodeZ_Fi_Rfc_Submit_Form_Input().invalidate();

                                   wdThis.wdFirePlugToConfirmView();

                                  }

                                  catch(Exception e){

                                        ms=e.getMessage();

                                        //ms = “failure2”;

                                        messageMgr.reportException(“Your information is not valid. Please provide valid information”,false);

                          
                                  }

                      Would be really greatful if you could give me your comments on this code.

                      I am not the JAVA person so that’s why I am forwarding the code to you. Maybe you could find the missing link here. I’ll forward these findings to him.

                      Cheers
                      Abhishek

                      (0) 
                      1. Raja Thangamani Post author
                        Abishek,

                        The way your Java folks passing the binary content to your RFC is not correct. Ask him to look at the method “onActionUploadFile” in this blog. I would ask him to refer this blog.

                        If still you face the issue please open a thread under “Webdynpro Java” forum.

                        Raja T

                        (0) 
                        1. Former Member
                          Hi Raja,
                                 Thanks for ur Blog.I copied the complete program and tried from R/3 side .I was able to attach the document for material Number, but the problem is i was not able to open the file .I uploaded MS Word Document and when i click on the attached document i am getting a version problem like that and i tried from different system also but no use.
                                 Can u please figure it out?
                          Thanks,
                          Gopi.
                          (0) 
  2. Former Member
    Hello,
    I am trying to upload a doc file as an attachment. If the content of the file is text file then it is able to upload it and display the content in r/3. But if the content of the doc is some image say .jpg or .bmp file then it is unable to display the content in r/3. Is there any restriction in the type of upload?

    Any help is highly appreciated

    (0) 

Leave a Reply