I am trying to call the form-recognizer API using SAPUI5 (Jquery / AJAX) post method. I am able to read the same pdf using RESTAPI client. The API when called from Javascript gives the below error.
The issue seems to be around data in the body of the ajax post method. Any suggestion/help is highly appreciated.
Error Message :
415 Unsupported Media Type
{"error":{"code":"2018","innerError":{"requestId":"a12dc9f8-b22f-4602-85d8-7330b16593f7"},"message":"Content
parsing error."}}
Javascript code :
onChange: function(oEvent) {
// var that = this;
var reader = new FileReader();
var file = oEvent.getParameter("files")[0];
var raw;
reader.onload = function (e) {
raw = e.target.result;
//alert(raw);
var sUrl2 = "https://formrecognizerforsap.cognitiveservices.azure.com/formrecognizer/v1.0-preview/custom/models/{mymodelid>/analyze";
jQuery.ajax({
type: "POST",
url: sUrl2,
context: this,
crossDomain: true,
data: raw,
beforeSend: function (xhr) {
xhr.setRequestHeader("content-type", "application/pdf");
xhr.setRequestHeader("ocp-apim-subscription-key", "my-subscription id");
},
error: function (jqXHR, textStatus, errorThrown) {
sap.m.MessageToast.show(errorThrown);
},
success: function (oData, status, jqXHR) {
sap.m.MessageToast.show(status);
}
});
};
reader.onerror = function (e) {
sap.m.MessageToast.show("error");
};
reader.readAsDataURL(file);
},
You could use atob javascript function to decode the Base64 string (link)
Example:
//plain text base64 WITHOUT datacontent and other stuff
let base64string = "JVBERi0xLjQKJ..."
let byteCharacters = atob(base64string);
jQuery.ajax({
type : "POST",
url : "<form recognizer url endpoint>",
context : this,
crossDomain: true,
data: byteCharacters,
beforeSend: function(xhr) {
xhr.setRequestHeader("ocp-apim-subscription-key", "<your_key>");
//To avoid specify pdf or image type use octet-stream
xhr.setRequestHeader("content-type", "application/octet-stream");
},
error : function(jqXHR, textStatus, errorThrown) {
console.error(errorThrown);
},
success : function(oData, status, jqXHR) {
console.info(status);
}
});
To get plain base64 string from pdf you could use this website to test: https://base64.guru/converter/encode/pdf
Related
Iam trying to upload file into document library but I can able to upload file but however column data was not reflecting into the column of document library.using rest Api every thing is working but my column value was not showing inside the column
here is my code
function createListItem() {
debugger;
var files = $("#attachment")[0].files;
if (files.length > 0) {
fileName = files[0].name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary = "MyDocumets";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
// Construct the Endpoint
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?#target='" + targetUrl + "'&$expand=ListItemAllFields";
uploadFileToFolder(files[0], url, function(data) {
var file = data.d;
DocFileName = file.Name;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type},
"DocumentType": $('#documenttype').val(),
"DocumentDescription": $("#Description").val(),
FileLeafRef: DocFileName //FileLeafRef --> Internal Name for Name Column
};
alert("File uploaded successfully!");
}, function(data) {
alert("File uploading failed");
});
} else {
alert("Kindly select a file to upload.!")
}
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileObj);
// Add the file to the SharePoint folder.
getFile.done(function(arrayBuffer) {
$.ajax({
url: apiUrl,//File Collection Endpoint
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function(data) {
success(data);
},
error: function(data) {
success(data);
}
});
});
}
// Get the local file as an array buffer.
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
i wanted to know how to enter value into the column and upload the document at the sane time
I am trying to upload a file using the FileUploader module in SAPUI5. The code I am trying to follow is from a blog https://blogs.sap.com/2016/11/08/step-by-step-on-how-to-use-the-sapui5-file-upload-feature/ however the code does not seem to execute the reader.onload function? It gets to reader.readAsDataURL(file) and dose not do anything? I am not sure where the problem lies and how to get it to work? Hekp will be much appreciated, there is a similar issue in the blog response but no help has been given.
XML
<u:FileUploader
id="VRCFileUploader"
value="{VRCFileUpload}"
placeholder="Please Attach document"
fileType="jpg,png,pdf"
style="Emphasized"
useMultipart="false" >
</u:FileUploader>
JS
function upload(evnt) {
var token;
var oView = this.getView();
var oFileUploader = this.byId("VRCFileUploader");
var sFileName = oFileUploader.getValue();
if (sFileName === "") {
sap.m.MessageToast.show("Please select a File to Upload");
return;
}
var file = jQuery.sap.domById(oFileUploader.getId() + "-fu").files[0];
var base64_marker = "data:" + file.type + ";base64,";
var reader = new FileReader();
//on load
reader.onLoad = (function(theFile){
return function(evt) {
//locate base64 content
var base64Index = evt.target.result.indexOf(base64_marker) + base64_marker.lenght;
// get base64 content
var base64 = evt.target.result.substring(base64Index);
var sTasksService = "SOME URL";
var sService2 = "SOME URL";
var oViewModel = oView.getModel();
var oContext = oView.getBindingContext();
var oTask = oViewModel.getProperty(oContext.getPath());
var oDataModel = sap.ui.getCore.getModel();
var sWorkitemId = JSON.stringify(oTask.wiId);
var service_url = sService2;
$.ajaxsetup({
cache: false
});
jQuery.ajax({
url: service_url,
asyn: false,
datatype: "json",
cache: false,
data: base64,
type: "post",
beforeSend: function(xhr) {
xhr.setRequestHeader("x-csrf-Token", token);
xhr.setRequestHeader("content-Type", file.type);
xhr.setRequestHeader("slug", sFileName);
xhr.setRequestHeader("WorkitemId", oTask.WiId);
},
success: function(odata) {
sap.m.MessageToast.show("file successfully uploaded");
oFileUploader.setValue("");
},
error: function(odata) {
sap.m.MessageToast.show("file Upload error");
}
});
};
})(file);
//Read file
reader.readAsDataURL(file);
}
In reply to Vortex:
Why is there an IIFE on the method being used on the onLoad Property?
Try to do somenthing like this:
reader.onload = event => {
let fileAsDataUrl = event.target.result;
....
};
I have written a function which sends a GET request and returns the response.
this.generateToken = function() {
var options = {
uri: 'http://localhost:10000/token',
method: 'GET',
headers: {
'Authorization': "YWRtaW46YWRtaW4="
},
};
request(options, function (error, response, body) {
var messageresponse = response.body.toString();
console.log(messageresponse); //I am able to print the response
return messageresponse;
});
};
I am able to print the value of 'messageresponse' variable inside request().
This function is being called from one of my test:
it('Post a GET request and generate a response', function () {
var response = commonFunctionObj.generateToken();
response.then(function(value){ //Getting below mentioned error on this line
console.log(value);
});
});
Getting error: TypeError: Cannot read property 'then' of undefined in teh calling function.
Can someone please help?
You need to create a promise and resolve it once to receive the response.
Look at the below code.
this.generateToken = function() {
var deffered = protractor.promise.defer(); //create a promise
var options = {
uri: 'http://localhost:10000/token',
method: 'GET',
headers: {
'Authorization': "YWRtaW46YWRtaW4="
},
};
request(options, function (error, response, body) {
var messageresponse = response.body.toString();
console.log(messageresponse);
deffered.fulfill(messageresponse); //Instead of returning the response message, fulfill the promise that we created early.
});
return deffered.promise; //return the created promise.
};
Now you can call the generateToken() method inside any of your test that will return a promise which is resolved only when the response is recieved from API call.
it('Post a GET request and generate a response', function () {
var response = commonFunctionObj.generateToken();
response.then(function(value){
console.log(value);
});
});
I think you can do it as follows;
this.generateToken = function() {
var deferred = protractor.promise.defer();
var options = {
uri: 'http://localhost:10000/token',
method: 'GET',
headers: {
'Authorization': "YWRtaW46YWRtaW4="
},
};
request(options, function (error, response, body) {
var messageresponse = response.body.toString();
deferred.fulfill(messageresponse);
});
return deferred.promise;
};
it('Post a GET request and generate a response', function () {
var response = commonFunctionObj.generateToken();
response.then(function(value){ //Getting below mentioned error on this line
console.log(value);
});
});
Explanation;
You can't use .then with generateToken's return. Because there is no return inside of that function. You need to make a promise (protractor.promise) for using then inside of that. Then, you can use .then with generateToken function.
You need to write print response logic in callback function, which is to resolve the promises or handling Asynchronous behavior
Code Snippet:
it('Post a GET request and generate a response', function () {
var response = commonFunctionObj.generateToken(function(err,res){
res.then(function(value){
console.log(value); //or return value
});
});
});
I want to authenticate the user_name and password field. the user_name and password field is stored in database with php. how to get the data from the server in ionic project.
Thanks in advance.
You can create a service script that can send post data to PHP and receive a JSON response.
Post data should be sent as an object containing element name and values in the following format:
var myObj = {username: 'username', password:'password'};
Below is a service example:
yourApp.service('YourService', function ($q, $http) {
return {
login: function (data) {
var deferred = $q.defer(),
promise = deferred.promise;
$http({
url: 'http://www.example.com/yourPHPScript.php',
method: "POST",
data: data,
headers: {'Content-Type': 'application/json'}
})
.then(function (response) {
if (response.data.error.code === "000") {
deferred.resolve(response.data.appointments);
} else {
deferred.reject(response.data);
}
}, function (error) {
deferred.reject(error);
});
promise.success = function (fn) {
promise.then(fn);
return promise;
};
promise.error = function (fn) {
promise.then(null, fn);
return promise;
};
return promise;
}
};
});
From your login controller you call the following code to use the service (make sure you add the name of the service to your controller declaration)
YourService.login(loginData)
.then(function (data) {
// on success do sthg
}, function (data) {
//log in failed
// show error msg
});
I'm trying to post a wall message from a local desktop application (I can't use the FB JS SDK).
Here's a a snippet of my code
var url = "https://graph.facebook.com/me/feed";
var params = "access_token=" + token + "&message=" + encodeURI(text);
$.ajax({
crossDomain: true,
data: params,
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
The request ignores the message parameter.
I receive a list of feeds as it were a GET request.
I've tried to set the parameters as map but it didn't help.
BTW - when using CURL (in C++) i manage to post the data correctly.
Any ideas why it ignores the parameters?
I would put the "params" into the data element like so:
var url = "https://graph.facebook.com/me/feed";
$.ajax({
crossDomain: true,
data: { access_token: token, message: text },
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
Let jQuery encode the parameters from there.
Below worked fine in Jquery 1.6.4 + jquery.mobile-1.0rc2 by setting $.mobile.allowCrossDomainPages = true; in mobileinit bind
$.ajax( {
url : "https://graph.facebook.com/me/feed",
type : "POST",
data : "access_token=" + your_access_token + "&message=my first wall post",
cache : false,
success : function(res) {
if (!response || response.error) {
alert("Couldn't Publish Data");
} else {
alert("Message successfully posted to your wall");
}
},
error : function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
}
});