cancel
Showing results for 
Search instead for 
Did you mean: 

Document Information Extraction - SAPUI5 Ajax POST call

ramesh_yuvashree
Explorer

I am trying to post a pdf to the "document-information-extraction/v1/document/jobs" for processing it and extracting texts. The post call is something like this -

var data1 = new FormData();

this.onuploadFile is the pdf file.

data1.append("file", this.onuploadFile,"mypdf"); data1.append("options", "{\"extraction\":{\"headerFields\":[\"documentNumber\",\"taxId\",\"taxName\",\"purchaseOrderNumber\",\"shippingAmount\",\"netAmount\",\"senderAddress\",\"senderName\",\"grossAmount\",\"currencyCode\",\"receiverContact\",\"documentDate\",\"taxAmount\",\"taxRate\",\"receiverName\",\"receiverAddress\"],\"lineItemFields\":[\"description\",\"netAmount\",\"quantity\",\"unitPrice\",\"materialNumber\"]},\"clientId\":\"c_00\",\"documentType\":\"invoice\",\"enrichment\":{\"sender\":{\"top\":5,\"type\":\"businessEntity\",\"subtype\":\"supplier\"},\"employee\":{\"type\":\"employee\"}}}");

var settings = { "url": "/DIC_trial_API/document/jobs", "method": "POST", "timeout": 0, "headers": {"Authorization": "Bearer "+bearerToken }, "processData": false, "mimeType": "multipart/form-data", "contentType": false, "data": data1 };

$.ajax(settings).done(function (response) { console.log(response); });

The response is "400 Error", with message as "{"error": {"code": "4", "message": "Required form-data not provided.", "details": [{"code": "0", "message": "options"}]}}".

Can anyone help if there's anything wrong with the formdata or post call method?

harianantha
Participant
0 Kudos
Hi Ramesh,

I am getting CORS issues when I use the direct AI swagger URI by using XMLHttpRequest. How did you use this service for POST?

Thank you

Accepted Solutions (1)

Accepted Solutions (1)

tobias_weller
Advisor
Advisor

Hi Ramesh,

Can you try stringifying the JSON before adding it to the form?

The following code works fine here:

 var form = new FormData($('#fileinfo')[0]);
                form.append('file', $('input[type=file]')[0].files[0]);

                var options = {
                    "extraction": {
                        "headerFields": [
                            "taxId",
                            "taxName",
                            "purchaseOrderNumber",
                            "shippingAmount",
                            "netAmount",
                            "senderAddress",
                            "senderName",
                            "grossAmount",
                            "currencyCode",
                            "receiverContact",
                            "taxAmount",
                            "taxRate",
                            "receiverName",
                            "receiverAddress",
                            "deliveryDate",
                            "paymentTerms",
                            "senderBankAccount"
                        ],
                        "lineItemFields": [
                            "description",
                            "netAmount",
                            "quantity",
                            "unitPrice",
                            "materialNumber"
                        ]
                    },
                    "clientId": "c_00",
                    "documentType": "invoice",
                    "receivedDate": "2020-02-17",
                    "enrichment": {
                        "sender": {
                            "top": 5,
                            "type": "businessEntity",
                            "subtype": "supplier"
                        },
                        "employee": {
                            "type": "employee"
                        }
                    }
                };

                stringified_options = JSON.stringify(options)
                console.log(stringified_options)

                form.append("options", stringified_options);

                var settings = {
                    "url": "http://XXXXXXXXX/document-information-extraction/v1/document/jobs",
                    "method": "POST",
                    "timeout": 0,
                    "headers": {
                        "Authorization": "Bearer {{token}}"
                    },
                    "processData": false,
                    "mimeType": "multipart/form-data",
                    "contentType": false,
                    "data": form
                };

                $.ajax(settings).done(function (response) {
                    console.log(response);
                });


 

Best regards
Tobias

ramesh_yuvashree
Explorer
0 Kudos

Hi Tobias,

Thanks for the code. So, the form element of Fileuploader is used in this case while creating a formdata. I am using a fileuploader and navigator.camera/image control to capture pdf and image respectively. The formdata looks like -

But, the content type still goes as "text/plain".

	var data1 = new FormData($('#container-cordova---View1--fileUploader-fu_form')[0]);
				data1.append("file", $('input[type=file]')[0].files[0]);
					data1.append("options", stringified);
	var settings = {
				"method": 'POST',
				"url": "/DIC_trial_API/document/jobs",
				"timeout": 0,
				"headers": {
	"Authorization": "Bearer " + bearerToken
				},
				"contentType": false,
                                "data": data1,
                                "mimeType": "multipart/form-data",
				"processData": false
			};
			$.ajax(settings).done(function (response) {
				console.log(response);
			});
harianantha
Participant
0 Kudos

Hi Tobias,

I am getting CORS issue when I use the direct AI swagger uri by using xmlHTTPRequest. How to solve this? and Can you please help me in creating a destination the sap BTP for this AI Dox service? I want to use the destination in order to use this DOX service in the SAP MDK app.

Thank you so much!

tobias_weller
Advisor
Advisor
0 Kudos

Hi Harikrishna,

Could you create an incident on component CA-ML-BDP? It's tricky to analyze this issue here.

Best,
Tobias

Answers (3)

Answers (3)

Hey Ramesh,

looks exactly like the example postman creates when sending something to the endpoint.
We sometimes see that there is a problem with the "multipart/form-data".
Can you try to workaround this and try again?

Thanks and best regard,
Christoph

ramesh_yuvashree
Explorer
0 Kudos

Hi Christoph,

I read somewhere that if we set content type as undefined, it would pick up the type based on data being sent. So, the code looks like this, now -

jQuery.sap.domById(fileuploader.getId() + "-fu").setAttribute("type", "file"); data1.append("file",jQuery.sap.domById(fileuploader.getId() + "-fu").files[0]); 
var blob = new Blob([JSON.stringify(options)], {type : 'application/json'}); 
data1.append("options",blob); 
jQuery.ajax( { url: "/DIC_trial_API/document/jobs", data: data1, "headers": { "Content-Type":undefined,  "Authorization": "Bearer "+bearerToken }, cache: false,  processData: false, method: 'POST',
success: function(data) { 
console.log(data); }, 
error: function(err) { console.log(err); } });

And, the content type gets set to "application/x-www-form-urlencoded; charset=UTF-8" and form data looks empty - ty-formdata.jpg

And, when testing the API from swagger UI, the formdata looks like -

former_member675531
Discoverer
0 Kudos

Hi Ramesh,

Can you please help in how you created the client id ... i am getting error as client id does not exist

thanks

tobias_weller
Advisor
Advisor
0 Kudos

Apologies for the late reply.
You can find the API description for creating clients here: SAP Help
In addition, I can highly recommend using our Tutorials to get started with the service.

Best regards,
Tobias

tobias_weller
Advisor
Advisor
0 Kudos

Hi Ramesh,

This was just some test code to try it out, I don't have a full application available at the moment unfortunately. Does it work for you now?

Best regards
Tobias

ramesh_yuvashree
Explorer
0 Kudos

Hi Tobias,

Unfortunately, no. I tried various sample codes available on postman but to no avail. And, the parameters being passed looks fine as I had searched a lot on formdata and post methods. I will try further, nevertheless.

ramesh_yuvashree
Explorer
0 Kudos

Finally the issue got resolved. I was using Hybrid app toolkit to capture picture, which was causing the problem with formdata. Fileuploader provides camera option for capturing images. After switching off HAT extension, it worked fine. Thanks