Using the SAPUI5 UploadCollection to upload/download ArchiveLink files via Gateway
First off, disclaimer: this blog post contains my views only and are not reflective of my employer or anyone else. Now that’s out of the way, we can begin!
I was asked to build a prototype UI5 application where the user can view and download existing attachments for an ISU business partner from ArchiveLink, as well as upload them. In the process of researching the prototype, I came across many helpful blogs, but I thought I’d also share my experience since I haven’t seen my particular scenario documented end to end.
The requirement to get and create attachments in ArchiveLink is not new, so I won’t really dwell on that. Instead I will be focusing on how it all hangs together, and the tweaking I had to do to deal with the ever so temperamental UploadCollection.
First things first. I had to build RFC function modules (I know, gross) because the system I had to work with is pre NW 7.31. Normally it would be a clean Gateway hub scenario (where the data retrieval would be written in the ECC Gateway service and consumed by the hub), but in my case I’m calling the function modules in ECC from the hub Gateway service. These function modules are pretty much just wrappers that are RFC enabled and call the standard ArchiveLink function modules, such as ARCHIV_GET_CONNECTIONS, ARCHIVOBJECT_GET_URI, ARCHIVOBJECT_GET_TABLE, etc.
The next step was to build the Gateway service. This was pretty straightforward too, with just some tweaks to handle media types and streams. I basically had a Customer entity (unfortunately everything is in German but you’ll get the gist) which has an association with a CustomerFile entity. It’s via the CustomerFile entity that we can retrieve the value stream of the file, as well as perform the upload. In particular, note that for this to work, you need to set the entity that is handling the file content as a media type (see the checkbox below).
Other than that, the rest is as per any Gateway Service Builder project. After generating the classes and runtime objects, the next step was to redefine the methods required to handle the upload and download of content streams. I referred a lot this amazing blog by Peter Marcely, which also includes handy code snippets. You can find my code snippets below for the methods that I needed to redefine:
<Your model extension class>-DEFINE
METHOD define.
super->define( ).
DATA:
lo_entity TYPE REF TO /iwbep/if_mgw_odata_entity_typ,
lo_property TYPE REF TO /iwbep/if_mgw_odata_property.
lo_entity = model->get_entity_type( iv_entity_name = ‘KUNDEN_AKTE’ ).
IF lo_entity IS BOUND.
lo_property = lo_entity->get_property( iv_property_name = ‘Mimetype’ ).
lo_property->set_as_content_type( ).
ENDIF.
ENDMETHOD.
/IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_STREAM (note: I didn’t really need this for the UploadCollection as the URL is used to retrieve the document, but this was useful for testing. If you need to embed the content of the file, say in an image control then this would be useful).
METHOD /iwbep/if_mgw_appl_srv_runtime~get_stream.
DATA: ls_key TYPE /iwbep/s_mgw_name_value_pair,
lv_gp_id TYPE saeobjid,
lv_doc_id TYPE SAEARDOID,
ls_lheader TYPE ihttpnvp,
ls_doc TYPE zrcm_gw_file_info,
lt_docs TYPE TABLE OF zrcm_gw_file_info,
ls_stream TYPE ty_s_media_resource,
lv_filename TYPE string.
CASE iv_entity_name.
WHEN ‘KUNDEN_AKTE’.
READ TABLE it_key_tab WITH KEY name = ‘GP_ID’ INTO ls_key.
lv_gp_id = ls_key–value.
clear: ls_key.
READ TABLE it_key_tab WITH KEY name = ‘Arc_Doc_Id’ INTO ls_key.
lv_doc_id = ls_key–value.
CALL FUNCTION ‘ZRCM_GW_READ_DOCUMENTS’ DESTINATION <ECC_Destination>
EXPORTING
obj_id = lv_gp_id
sap_obj = ‘BUS1006’
IMPORTING
dokumente = lt_docs.
READ TABLE lt_docs INTO ls_doc WITH KEY object_id = lv_gp_id arc_doc_id = lv_doc_id.
ls_stream–value = ls_doc–content.
ls_stream–mime_type = ls_doc–mimetype.
lv_filename = ls_doc–arc_doc_id.
lv_filename = escape( val = lv_filename
format = cl_abap_format=>e_url ).
ls_lheader–name = ‘Content-Disposition’.
ls_lheader–value = ‘|inline; Filename=”{ lv_filename }”|’.
set_header( is_header = ls_lheader ).
copy_data_to_ref( EXPORTING is_data = ls_stream
CHANGING cr_data = er_stream ).
ENDCASE.
ENDMETHOD.
/IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_STREAM
METHOD /iwbep/if_mgw_appl_srv_runtime~create_stream.
DATA: ls_key_tab TYPE /iwbep/s_mgw_name_value_pair,
lt_key_tab TYPE /iwbep/t_mgw_name_value_pair,
ls_doc TYPE toadt,
ls_return TYPE bapireturn1,
ls_kundenakte TYPE zcl_zrcm_verbindung_mpc=>ts_kunden_akte,
lv_error TYPE string,
lv_filename TYPE toaat–filename,
lv_mimetype TYPE w3conttype,
lv_gp_id TYPE char10.
CASE iv_entity_name.
WHEN ‘KUNDEN_AKTE’.
READ TABLE it_key_tab WITH KEY name = ‘GP_ID’ INTO ls_key_tab.
lv_gp_id = ls_key_tab–value.
lv_mimetype = is_media_resource–mime_type.
REPLACE ALL OCCURRENCES OF ‘#’ IN lv_mimetype WITH space.
lv_filename = iv_slug.
REPLACE ALL OCCURRENCES OF ‘#’ IN lv_filename WITH space.
CALL FUNCTION ‘ZRCM_GW_STORE_DOCUMENT’ DESTINATION <ECC_Destination>
EXPORTING
ar_object = ‘/BME/V0043’
object_id = lv_gp_id
sap_object = ‘BUS1006’
doc_type = lv_mimetype
document = is_media_resource–value
filename = lv_filename
IMPORTING
outdoc = ls_doc
return = ls_return.
IF ls_return–type = ‘E’.
lv_error = ls_return–message.
RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
EXPORTING
textid = /iwbep/cx_mgw_busi_exception=>business_error_unlimited
message_unlimited = lv_error.
ELSE.
ls_kundenakte–arc_doc_id = ls_doc–arc_doc_id.
ls_kundenakte–filename = iv_slug.
ls_kundenakte–mimetype = is_media_resource–mime_type.
ls_kundenakte–gp_id = lv_gp_id.
kunden_akteset_get_entity(
EXPORTING
iv_entity_name = iv_entity_name
iv_entity_set_name = iv_entity_set_name
iv_source_name = iv_source_name
it_key_tab = it_key_tab
it_navigation_path = it_navigation_path
IMPORTING
er_entity = ls_kundenakte ).
copy_data_to_ref( EXPORTING is_data = ls_kundenakte
CHANGING cr_data = er_entity ).
ENDIF.
ENDCASE.
ENDMETHOD.
KUNDEN_AKTESET_GET_ENTITY
METHOD kunden_akteset_get_entity.
DATA: ls_key TYPE /iwbep/s_mgw_name_value_pair,
lv_arc_doc_id TYPE string,
lv_gp_id TYPE saeobjid,
lv_content TYPE xstring,
lv_bin_length TYPE sapb–length,
ls_doc TYPE zrcm_gw_file_info,
lt_docs TYPE TABLE OF zrcm_gw_file_info.
READ TABLE it_key_tab WITH KEY name = ‘GP_ID’ INTO ls_key.
lv_gp_id = ls_key–value.
CLEAR: ls_key.
READ TABLE it_key_tab WITH KEY name = ‘Arc_Doc_Id’ INTO ls_key.
lv_arc_doc_id = ls_key–value.
CHECK lv_gp_id IS NOT INITIAL AND lv_arc_doc_id IS NOT INITIAL.
CALL FUNCTION ‘ZRCM_GW_READ_DOCUMENTS’ DESTINATION <ECC_Destination>
EXPORTING
obj_id = lv_gp_id
sap_obj = ‘BUS1006’
IMPORTING
dokumente = lt_docs.
READ TABLE lt_docs INTO ls_doc WITH KEY arc_doc_id = lv_arc_doc_id.
MOVE-CORRESPONDING ls_doc TO er_entity.
er_entity–gp_id = lv_gp_id.
ENDMETHOD.
This is the POST URL I used to upload some content for testing:
/sap/opu/odata/sap/ZRCM_VERBINDUNG_SRV/KUNDEN_AKTESet(‘0000208999’)/$value
So far, so good.
Next I created a simple UI5 application that allows the user to view the attachments that exist, while also having the ability to upload new ones. The control that made the most sense was UploadCollection, which seems to be relatively new (read: buggy). In principle this was the perfect control for the use case, however when I started using it I realized that it’s still in its developmental stages. I referred to the UploadCollection example in SAPUI5 Explored, but please note that uses hard coded JSON data.
First thing I realized is when I disabled instantUpload, I lost the ability to display the existing attachments in a list. The list becomes the waiting area only for the attachments you will be uploading. That was rather annoying, because sometimes you want to check the files before you decide to upload them, as well as being able to see what files already exist. Perhaps this will be improved in a later release, but for now I just had to leave instantUpload on.
Another thing I noticed: after the UploadCollection is instantiated, you can no longer set the upload URL dynamically. This means you either hardcode it in the view definition (yuck), or you set it once at initialization, which is what I ended up doing. I find it strange that we are given the setter method, but when you use it after instantiation, you get this error:
Then there’s the CSRF Token. I get why we need to use these, but to have to set it manually in the code is just mind boggling. Essentially I had to retrieve the CSRF Token in an AJAX call, and store the token to be sent with the upload request. This seems to be the case also with the FileUpload control as there are loads of other posts describing the same workaround. It would be nice if this was all handled automatically in the standard control.
The final thing I had to tweak was the completed upload event handler. I expected to have access to the response from the upload request (similar to reading the model) in this event, since it is triggered after a successful upload. Think again. If you leave this method empty, the status of the upload stays at 99% forever. I didn’t really want to rebind the whole UploadCollection aggregation each time an upload is completed, since the list could load quite slowly and appear strange to the user (while a new file is uploading, it appears at the top of the list, but after rebinding it goes somewhere else). In the end I had to resort to rebinding because it was the cleanest way. I added a busy dialog with a delay so the user wouldn’t see the file hop from the top to somewhere else.
Below are some screenshots of the application in action:
Here are the key events for UploadCollection:
onBeforeUploadStarts: function(oEvent) {
// Stellen die Kopf Parameter slug
var oCustomerHeaderSlug = new sap.m.UploadCollectionParameter({
name : "slug",
value : oEvent.getParameter("fileName")
});
oEvent.getParameters().addHeaderParameter(oCustomerHeaderSlug);
_busyDialog.open();
},
onUploadComplete: function(oEvent) {
var sUploadedFile = oEvent.getParameter("files")[0].fileName;
var location = oEvent.getParameter("files")[0].headers.location;
var index = location.indexOf("/KUNDEN_AKTESet");
var path = location.substring(index);
var oCollection = oEvent.getSource();
var collectionPath = "/KUNDENSet('" + _gp_id + "')/AKTEN";
var oTemplate = this.byId(_collectionItemId).clone();
_collectionItemId = oTemplate.getId();
oCollection.bindAggregation("items", {
path: collectionPath,
template: oTemplate
});
setTimeout(function(){
_busyDialog.close();
MessageToast.show(_oBundle.getText("dokumentHochgeladen"));
}, 3000);
},
onChange: function(oEvent) {
// Stellen das CSRF Token wenn ein File hinzugefügt ist
var oUploadCollection = oEvent.getSource();
var oCustomerHeaderToken = new UploadCollectionParameter({
name : "x-csrf-token",
value : _csrfToken
});
oUploadCollection.addHeaderParameter(oCustomerHeaderToken);
},
So there you have it. A few tweaks here and there but now it functions quite well. I hope to see future improvements in this control, as it is quite a handy one, and I’d personally like the methods that are not allowed to be removed (why tease me with something I can’t actually use).
I hope this post has helped shed some insight if you are looking into the same scenario.
Hi Joana,
Really useful blog, thanks for the effort.
raghav
Thanks I'm glad it helped!
Hi Joanna,
please send the code for inside of this function module CALL FUNCTION 'ZRCM_GW_READ_DOCUMENTS' DESTINATION <ECC_Destination>..
this code is very helpful to get files from the DMS system.
Regards
Shankar.
Hello Shankar,
As mentioned in the start of the blog post, I used the standard ArchiveLink function modules to retrieve the data. You would have to work out yourself what parameters to supply, as it would vary based on what type of business object you're dealing with.
In short, the sequence I used was to call these function modules in the shown order:
If you use the wizard with these function modules you will see about the same thing that's in my code.
Hope this helps.
Regards,
Jo
Hello Joanna,
I am creating a simple application to load files from UI5 to gatway.
I redefined update_Stream and get_Stream. now i can upload/downlod files from gatwayclient.
Then I created UI5 Application with UploadCollection.
onChange(){
setting the x-csrf-token
}
onBeforeUpload(){
setting the file name
}
and uploadUrl i set like:
<UploadCollection
id="UploadCollection"
maximumFilenameLength="55"
multiple="true"
uploadUrl="proxy/http/<host>:<port>/sap/opu/odata/sap/ZZTEST_SRV/attchmentSet"
....
...
</UploadCollection>
Running the app on upload files: i am getting error
responded with a status of 500 (Server Error)
FileUploader.js:6 POST http://localhost:50868/Text/proxy/http/<host>:<port>/sap/opu/odata/sap/ZZTEST_SRV/attchmentSet 500 (Server Error)
could you please guide me to correct the uploadUrl.
Thanks and Best Regards,
Abhi
Hi Abhi,
It looks like you are trying to test from a local host. Have you setup your proxy definition so you can access the Gateway system? It should be in web.xml.
Also, normally a 500 error is an error on the server side, so you would either be able to find more information in the Gateway logs, or try and debug.
Regards,
Jo
Hello Jonna,
Thanks a lot for your reply. I checked log and found that create_stream method should be implemented. After implementing the method now files are getting store in database.
But in UI busy state is always on with message : Upload completed. Please wait for the server to finish. Could you please let me know how to stop the busy indicator.
PS: When i tested through gateway client update_Stream is getting called because of PUT so i though it will work for uploadcollection too, but in case of Uploadcollection POST is getting triggered so we should have create_stream method.
Thanks and Best Regards,
Abhi
Hello Jonna,
Could you please answer my query sap.m.uploadCollection
Thanks and Best Regards,
Abhishek
Unless you are asking for clarification/correction of some part of the Document, please create a new Discussion marked as a Question. The Comments section of a Blog (or Document) is not the right vehicle for asking questions as the results are not easily searchable. Once your issue is solved, a Discussion with the solution (and marked with Correct Answer) makes the results visible to others experiencing a similar problem. If a blog or document is related, put in a link. Read the Getting Started documents (link at the top right) including the Rules of Engagement.
NOTE: Getting the link is easy enough for both the author and Blog. Simply MouseOver the item, Right Click, and select Copy Shortcut. Paste it into your Discussion. You can also click on the url after pasting. Click on the A to expand the options and select T (on the right) to Auto-Title the url.
Thanks, Mike (Moderator)
SAP Technology RIG
Thanks Michael Appleby,
I will take care of this going forward.
Regards,
Abhishek
Much appreciated Abhishek!
Hi Joanna,
It is a very interesting blog. I am working on a similar PoC. I have to retrieve a document stored using archivelink. For this I am using SAPUI5 and oData. My oData service works fine. I am using
ARCHIV_GET_CONNECTIONS and ARCHIV_GET_CONNECTIONS functions to display the stored document. Normally, if you run this FM with the correct parameters, the document opens up in the browser automatically.
How do I handle this in the SAPUI5 frontend?
Hi Joana,
How can we use UploadCollection with rest service to upload/download files?
Thanks,
Azhar
Hi Joanna,
As per this blog, we can use link
sap/opu/odata/sap/ZRCM_VERBINDUNG_SRV/KUNDEN_AKTESet(‘0000208999’)/$value to upload the attachment in ECC.
Can you please help me to know where exactly I have to put this link.
I tried putting this URL in:
I tried both the approaches but my CREATE_STREAM method of DPC_EXT class is not getting called.
You views on this will be really helpful.
Regards,
Harish
i am also getting same issue
Hi Former Member
I have the same requirement as yours. I have trouble creating the document in the content repository. Can you pls tell me that the FM that you have used ‘ZRCM_GW_STORE_DOCUMENT’ is the copy of which standard FM??
thanks in advance.
regards,
Shaddha.
Hi Joanna,
Can you please let me know how to make synchronous or asynchronous from ui5 to ODATA for this uploadCollection functionality. i could not find in UI5 demokit.
Thanks & Regards,
Rakshith
Hi,
could anybody show how to get the CSRF Token? I have tried different ways, but without success.
Thanks & Regards
Yu
Hi ,
can anyone let me know about the upload collection ,what is the maximum file size that can be included in each of the files in case of multiple files.
maxfileSize="?" multiple="true" and it is more than 10 files
Please help me out in this.
thanks,
Akhil Jain
Hi,
Coud you please show me (or send via email) your full XML view and JS controller? I need to do the same thing, but I just cant get the binding right.
Thank you
Tu
Hi,
i could provide you with my recent stage of development regarding the upload collection control, without any warantees or guarantees
So far, uploading a singel PDF works, and also uploading multiple files work but i am still figuring out, how to cut the incoming stream into pieces such that i can identify the single files…
It is tricky to set the right things in the right event handlers…
So, regarding the UI part, i have in the View:
Still, an issue persist that i am not able to provide the UploadUrl dynamically... so it is still under construction. But as a test, it is hard-coded.
For the controller, it is really important where to add certain additional header-Parameters...to figure this out took me some days! 🙂
as of today, this works for me.. it may change with a later version of SAPUI5, as for me, these are bugs, that setting those parameters doesn't work as well in other events previous to the upload itself...
Controller:
all the other, commented parts did not work at this point/event!! So most of the time I wasted to figure this out. Therefore, it is still in the code 😉
At this point i just want to pay credit to all those people that wrote a number of blogs on the fileUploader and the UploadCollection on different Forums.. !
Hope it could help!
Cheers,
Aleks
Hello to all,
I implemented the UploadCollection and so far, i am able to sent files to the backend (SEGW/SE80 OData-Service)
does anybody of you know how to distinguish the incoming files later in the backend? I have access to the content (is_media_resource-value), but how can i "cut" the content into the distinct files i sent originaly? Shall I use a function module for this? Some Xstring_to... ?
Thank you in advance!
Best regards,
Aleks
I have found a solution, thanks to the original author of the post and focusing while reading 😉
URL: It can be set in the onInit-Method
Several files:
In Principle, for each file an own/distinct HTTP-Post is fired. Each File will be represented internally as an aggregation items -> UploadCollectionItem, and those have a property (check the api) called fileName, that you can use to set the slug in onBeforeUploadStarts, that is called for each item/file. So the filename can will be transmitted in the slug for each file seperately. Still to go for grouping those calls, as I may run into some lock-issues for real-world scenario. I will update my previous contribution to show the "final" coding.
Cheers,
Aleks
Hello Aleksandar Mijailovic ,
I have a similar requirement to use Upload Collection to send multiple files to the backend.
Can you please share with us how did you manage to differentiate the files you receive in the backend?
Thank you in advance
Sérgio Fraga
Hola Sergio,
sorry for the late reply!
Do you still need this? If yes, i can post the solution, my controller etc.
Cheers,
Aleks
Hi Aleksandar Mijailovic ,
Thank you for the reply.
It would be great to see how you have approached the problem.
So yes, if possible, maybe a specific blog?
Thanks
Hi Sergio,
somehow, i don't get notifications if somebody comments to my post. I will try to write a blog post during the weekend, if it is enough for you?
Cheers,
Aleks
Hi Aleksandar Mijailovic ,
No rush on this one!
By creating a specific blog with your learnings we all can learn and become better at OData development in SAP.
Thank you for your reply and availability!!
Hola Sergio,
thanks, i will start with it during the week. I went to the Hackaton/Connect2019 in Berlin..it was tough and time- & ressources-consuming, but very very cool! Unfortunately, i couldn't do the blog during that time.
Your welcome!
HI All,
I did the same as given by "Aleksandar Mijailovic", i can able to upload but not able to download or actuallly i wanted to display in the next tab the uploaded file .
Attached screenshot.
Could you please help on this what wrong i did .
Hi guys,
sorry for the late reply. I will try to upload my complete code. It is some time ago, since I worked on this, so no guarantee.
For displaying previously uploaded files, you need to construct the URL such that for each file, upon click, a $value call is fired. So, you first need to get all files that are there in the backend, by firing a get_entity-call. This will give you the filename, but more importantly, the key-fields (like Id Head and DocumentId in my case). When having the key-fields, the URL can be constructed using a formatter function. Then this URL will be called upon click on the Item of the UploadCollection. This is roughly the approach I was using back in the days. CAUTION/Disclaimer: This was SAPUI5-Version 1.54 or so. Maybe it changed for newer Versions, so no guarantee/responsibility, neither I am claiming that this is best practise and completely working etc.
Data model looks like this:
I created an emplty json model, and a source file "DocItems", which was later filled by the get_entity-call:
path: model/DocItems.json (it is in the model-folderm below webapp)
{
"DocItemsData": []
}
The model is just an file in the Model-folder:
It has to be registered in the manifest:
In the data sources section of the manifest:
"DocItems": {
"uri": "model/DocItems.json",
"type": "JSON"
}
in the model-section of the Manifest:
"itemsData": {
"type": "sap.ui.model.json.JSONModel",
"dataSource": "DocItems",
"settings": {
"defaultBindingMode": "TwoWay"
},
"preload": false
}