willard Chingarande
willard Chingarande

Reputation: 65

upload a file in SAPUI5 and send to Gateway server

I am having difficulties trying to figure out a way to send uploaded file and send it to a Gateway server. I am using the basic FileUploader control.

    ***<u:FileUploader
        id="fileUploader"
        name="myFileUpload"
        uploadUrl="upload/"
        width="400px"
        tooltip="Upload your file to the local server"
        uploadComplete="handleUploadComplete"/>
    <Button
        text="Upload File"
        press="handleUploadPress"/>***

And in the controller I have the following event handler

     ***handleUploadPress: function(oEvent) {
        var oFileUploader = this.getView().byId("fileUploader");
        oFileUploader.upload();
    }***

What code should I add after oFileUploader.upload() to have an xstring that I can pass to my attachment property of my OData srvice

Thank you

Upvotes: 0

Views: 8779

Answers (1)

jpenninkhof
jpenninkhof

Reputation: 1920

The first thing to do is to make sure that you have a gateway service that is able to handle media types and streams. To set this up you need to set the entity that is handling the file content as a media type and get the logic in place that deals with streams (CREATE_STREAM). You can find more information on how to do this in this SCN blog.

In your UI5 application, you will have to set the URL of the upload control to e.g. /sap/opu/odata/sap/AWESOME_SERVICE/Customers('0000123456')/$value so that the file is handled by the CREATE_STREAM method that you just implemented.

When the upload is eventually taking place, you need to deal with two header parameters; the slug and the CSRF token. The slug header should be set to e.g. the filename, while the CSRF token needs to be retrieved using a pre-flight request. To set the headers, you could use something like this:

oFileUploader.addHeaderParameter(new FileUploaderParameter({
    name: "x-csrf-token",
    value: _csrfToken
}));

The slug header parameter could be set in a similar way and should contain something that identifies the file, e.g. filename or id.

To determine the CSRF token, you could do something like this:

var _csrfToken = "";
jQuery.ajax({
    url: "/sap/opu/odata/sap/AWESOME_SERVICE",
    headers: {
        "X-CSRF-Token": "Fetch",
        "X-Requested-With": "XMLHttpRequest",
        "DataServiceVersion": "2.0"
    },
    type: "GET",
    contentType: "application/json",
    dataType: 'json',
    success: function(data, textStatus, jqXHR) {
        _csrfToken = jqXHR.getResponseHeader('x-csrf-token');
    }
});

With the right header parameters in place, sending the file to a properly configured gateway entity should do the trick to get your file uploaded.

Upvotes: 4

Related Questions