Generate pdf using stream in Angular - angularjs

I am trying to generate pdf and display inside any Div, I am getting binary data from server but when I try to convert that stream it says failed to load pdf.
I googled it and saw response of many people saying use responseType: 'arraybuffer' but I am getting object from server and extracting binary from it so I can't use it, though I tried with this approach as well but it didn't work.
Here is my controller code:
correspondenceService.getCorrespondenceDocument(id).$promise.then(function (data) {
var file = new Blob([(data[0].documentBytes)], { type: 'application/pdf' });
var fileURL = window.URL.createObjectURL(file);
vm.content = $sce.trustAsResourceUrl(fileURL);
window.open(fileURL);
}, function (reason) { });
}
This is Service:
getCorrespondenceDocument: function (correspondenceId) {
return $resource(correspondenceUrl + "getCorrespondenceDocuments").query({ correspondenceId: correspondenceId });
}
and this is my webApi:
[Route("getCorrespondenceDocuments")]
[HttpGet]
public async Task<IEnumerable<Document>> GetCorrespondenceDocumentsAsync(int correspondenceId)
{
var documents = await _correspondenceFacade.GetCorrespondenceDocumentDetailsAsync(correspondenceId);
return Mapper.Map<IEnumerable<Document>>(documents);
}
Trying to display like this on View:
Please let me know where I am doing mistake. Many thanks in advance.
Regards,
Vivek

Finally I managed to do it. Problem is I was passing 3 parameters in $http.get(), now I am passing 2 parameters only.
getCorrespondenceDocuments: function (correspondenceId) {
return $http.get(correspondenceUrl + 'getCorrespondenceDocuments' + '?correspondenceId=' + correspondenceId, { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
Though I don't like to pass any parameter using this "?" and specifying id but I couldn't find any solution to this problem.
Many thanks guys for going through my post.
Regards,
Vivek

Related

Angular Onsen UI Ajax call

I am beginning to learn writing apps using Monaca and I have a sample application I am editing which is written in Onsen and Angular.
I would like to be able to get data from a remote file on my server when needed as data will change regularly.
What is the correct way to get the data via Ajax or HTTPRequest? THe following doesn't seem to work.
function getDataPullCheck() {
alert("getDataPullCheck");
angular.request({
url: "https://***my file***",
method: 'POST',
success: function (data) {
console.log(data);
alert{data};
},
error: function (x, t, m) {
alert{'Error'};
}
});
}
Could someone correct my code or point me in the direction of a good tutorial for getting remote data into the app?
Many thanks.
So I realised this can be done in simple JS.
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = false;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
displayResult(jsonResponse,ptype);
}
};
xhttp.open("GET", <<MYFILE>>, true);
xhttp.send();

Query: Response does not match configured parameter

i am getting response error please any one try to solve my problem. i am trying to solve that but i didn't solve this. please help me.
thanks in advance
$scope.init = {};
var Call = $resource('../api/Home', {}, { query: { method: 'POST', isArray: false} });
$scope.init = function () {
//alert("hi");
$scope.selected = "";
var x = $('#txtSearch').val();
var _ReqObj = new Object();
_ReqObj.id = x;
_ReqObj.Meth = "GJ";
Call.query({}, _ReqObj,
function (response) {
alert(response);
alert(_ReqObj);
if (response == '') {
// alert('no data');
window.location.replace("index.html");
}
else {
//$scope.click = response;
$scope.init = response;
}
},
function (error) {
window.location.replace("index.html");
}
);
};
The error message says: "Expected response to contain an object but got an array"
this means: Your request (Call.query) does expect a single object (you are setting isArray: false). But the server sends an array. So the server is not sending what the function expects!
There is some hints I want to give you:
Why are you using query? A query is normally used to get an array from the server, not a single object. Why are you using query at all?
Do you really want a single object or do you want a list of objects?
What is the server sending? Open the development console in your browser (ctr+alt+I in Chrome) and click on the Network tab. Click on the request (../api/Home) and check the response from the server. You should see the json objects or arrays the server sent as a response to your request.

How to return image from $http.get in AngularJS

In my controller I call a service that returns a promise
var onComplete = function(data) {
$scope.myImage = data;
};
In my service I make a call to get the image by passing url directly to the image itself:
return $http.get("http://someurl.com/someimagepath")
.then(function(response){
return response.data;
});
All the calls are succeeding and the response.data appears to be holding in an image inside:
����JFIF��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 90
��C

��C
����"��
���}!1AQa"q2���#B��R��$
although I'm not sure if it actually does because I'm having trouble displaying it. I've tried (inside index.html)
<img ng-src="{{myImage}}">
and
<img ng-src="{{myImage}}.jpeg">
and
<img ng-src="data:image/JPEG;base64,{{myImage}}">
Ideas?
Is it possible to return an actual image from $http.get and convert its response back to image (jpeg, etc.)
Thanks!
None of the methods seems to be complete, this is a complete solution:
$http({
method: 'GET',
url: imageUrl,
responseType: 'arraybuffer'
}).then(function(response) {
console.log(response);
var str = _arrayBufferToBase64(response.data);
console.log(str);
// str is base64 encoded.
}, function(response) {
console.error('error in getting static img.');
});
function _arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
Then I am able to use it directly:
<img data-ng-src="data:image/png;base64,{{img}}">
The function to convert arraybuffer into base64 is directly taken from ArrayBuffer to base64 encoded string
Just in case anyone needs it.
In my case, I had to send the request through angular's $http service, because of various transformers and other fancy stuff we do with it.
So based on the Mozilla's guide mentioned earlier, I came up with the following solution:
let getImageDataURL = (url, imageType = 'image/jpeg') => {
return $http.get(url, {responseType: 'arraybuffer'}).then((res) => {
let blob = new Blob([res.data], {type: imageType});
return (window.URL || window.webkitURL).createObjectURL(blob);
});
};
The basic idea is to set the responseType property of the underlying XHR request and the convert the binary content to data URL.
The image that's coming back is in binary encoding, rather than Base64.
Understandably, <img> tags don't support sourcing from binary through attributes, so you'll have to look at another solution.
You could try converting the binary encoding to Base64 at the client side using TypedArrays together with the btoa function. Then you'd be able to use
<img ng-src="data:image/JPEG;base64,{{myImage}}">
This guide a by Mozilla covers making an XHR request for and image and reading it directly into a UInt8Array. It should be a good starting place.
It's written for plain old Javascript, but translating it to Angular should be a good exercise if you are just learning the ropes.
By way of https://stackoverflow.com/a/43032560/418819, you can use "blob" as the responseType and very neatly get the data url with a FileReader.
$http.get( url, { responseType: "blob" } ).then((result) => {
var reader = new FileReader();
reader.readAsDataURL( result.data );
reader.onload = function (e) {
return e.target.result;
};
});
You can reference it like so:
<img data-ng-src="{{img}}">

in Backbone, is it possible to tell fetch that it if it reads content that is content-type:'text/plain' to read it as JSON

I have a webserver that is sending back json files as 'text/plain'. I unfortunately can't adjust this. Can I tell a backbone fetch on a collection to read it as JSON even if it has this content/type? Like an emulateJSON for the response?
thx
Basically want to fix this:
Here's my backbone code that I'm having problems with (total backbone noob so I know there is most likely something wrong with how I'm handling this):
var MyItemList=Backbone.Collection.extend({url:'items.json', model:MyItem,
// not sure if I need this?
parse: function(response) {
return response.results;
}
});
var AppRouter=Backbone.Router.extend({
routes:{'':'list','detail/:id':'detail'},
list:function(){
var itemList=new MyItemList();
itemList.fetch({ dataType:'json',
error: function () {
console.log("error!!");
},
success: function () {
console.log("no error");
}
}).complete(function () {
console.log('done');
console.log('length1:' + itemList.length);
});
console.log('length2: '+ itemList.length);
}
my json:
Remove parse method:
With Parse:
Backbone uses jQuery.ajax under the hood for the ajax requests.
So you need to use the dataType: 'json' options to specify how jQuery should treat the response when you are calling fetch:
yourCollection.fetch({
dataType: 'json'
});

Angular $resource PUT method, can't make it work

I use a REST api and I'd like to update on of my project objects with a PUT request. The request is supported in the API, and I'm trying to use $resource to PUT the data, but it doesn't seem to work. Here is what I do :
var projectResource = $resource('/api/projects/' + projectId, {update: {method: "PUT"}});
$scope.editProject = function(editedProject) {
projectResource.$update(editedProject);
}
Where editedProject is the project with the new values, filled by a form in a webpage. I know there is something wrong in my projectResource declaration, but I don't find what. Help !
Try this:
$resource('/api/projects', { id: projectId }, {
update: { method: 'PUT' }
});
$resource cannot make 'PUT' method, cuz of No 'Access-Control-Allow-Origin'. you can only found the 'OPTIONS' in the networks.In this case, you need to create your PUT call:
var data = $resource('someURL', { jobId: '#jobId'}, { 'update': { method:'PUT' }});
data.update(objectYouWannaUpdate);

Resources