Prints out Gibberish PDF file. Angular 6 - javascript

this is how the binary file looks like.
This is how im subscribing to the method that fetches pdf blob file
public downloadDoc(token: any, docNumber: number) {
this.loading = true;
this._docService.getDocumentStreams(token, docNumber).subscribe(res => {
this.loading = false;
let file = new Blob([res._body], {
type: 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
console.log(res)
window.open(fileURL);
}, (error => {
console.log(`failed to download document: ${error}`);
}))
}
heres the method in service
public getDocumentStreams(token: any, docNumber: number): Observable < any > {
const body = {
'DocNo': docNumber,
'StreamNo': 0
};
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('TenantName', 'idl');
headers.append('UseToken', '1');
headers.append('Authorization', 'Basic ' + window.btoa('webapi' + ':' + token));
headers.append('responseType', 'arraybuffer'
as 'json');
return this.http.post(`${this._therefore_apiBase}/GetDocumentStreamRaw`, body, {
headers: headers
}).pipe(
map((response) => {
return response;
}));
}
This prints out a gibberish pdf file what could be the problem

Related

how to get file content through c# in node js

I am getting blob of pdf file from other server which is on C# in node server when I am converting it to array buffer it's size is different from C# array buffer size and when I am opening it to browser it gives error "Failed to load PDF document."
This is my server side code
async post(param: any, body: any, endPoint: string, queryParams: string = '')
{
try
{
if(queryParams == '') queryParams = param.destinationSlug + '/' + param.mainBranchId;
const url = splendidAccountsEndPointsEnum.baseUrl + queryParams + endPoint;
const offset = new Date().getTimezoneOffset().toString();
const headerConfig = { headers: { 'X-Api-Key': param.apiKey, 'X-Api-Secret': param.apiSecret, 'X-App-Id': config.get<string>("splendidXAppId"), LocalDateTimeOffset: offset }}
const response = await axios.post(url, body, headerConfig)
.then(function (response: any)
{
return response?.data;
})
.catch(function (error: any)
{
console.log(error);
return error;
});
if (response?.status === 200)
{
console.log('success');
return response?.data;
}
return response;
}
catch (err)
{
console.error(err);
console.log(err);
return err;
}
}
And this is my client side
let response = this.orderService.generateInvoicePrinting(this.selectedRows)
.subscribe((res) => {
var file = new Blob([res], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
saveAs(file, "invoices.pdf");
window.open(fileURL);
this.pdfSrc = fileURL;
this.showPdf = true;
this.showSuccess('Invoices have been generated successfully.');
this.selectedRows = [];
},
error => {
this.showError('Invoices have not been generated successfully.');
});
generateInvoicePrinting(orders: any): Observable<any>
{
const url = `${environment.apiUrl}api/Order/printInvoices/pdf`;
return this.http.post(url, orders, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), observe: 'response', responseType: 'blob' }).pipe(
map(res => res.body),
);
}

Angular HTTP Request From File From GitHub

In a Git repository I have a Json file. I want to request it so I can parse it into a data object in my Angular App.
When I use the Git V3 API to retrieve content of the file I get this:
{
"name": "file.json",
"path": "path/to/file.json",
"sha": "e54635a380b571b785e802819a3aeeaa569891d9",
"size": 5571,
"url": "https://github.foo.com/api/v3/repos/MyOrigin/the-repo/contents/path/to/file.json?ref=master",
"html_url": "https://github.foo.com/MyOrigin/the-repo/blob/master/path/to/file.json",
"git_url": "https://github.foo.com/api/v3/repos/MyOrigin/the-repo/git/blobs/14524524524352345",
"download_url": "https://github.foo.com/raw/MyOrigin/the-repo/master/path/to/file.json",
"type": "file",
"_links": {
"self": "https://github.foo.com/api/v3/repos/MyOrigin/the-repo/contents/path/to/file.json?ref=master",
"git": "https://github.foo.com/api/v3/repos/MyOrigin/the-repo/git/blobs/24352435234523452345",
"html": "https://github.foo.com/MyOrigin/the-repo/blob/master/path/to/file.json"
}
},
The above I retrieved using this script:
getContent(team: string): Observable<Content> {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({ headers: headers });
this.Url += '/' + team + '.json';
return this._http.get(this.Url, options)
.map((response: Response) => {
const data = response.json();
return {
name: data.name,
git_url: data.git_url,
html_url: data.html_url,
download_url: data.download_url,
type: data.type,
} as Content
})
.catch(e => {
if (e.status === 401) {
return Observable.throw('Unauthorized');
}
if (e.status === 404) {
return Observable.throw('Not found.');
}
});
}
From the above response are a few URLs about the file. download_url I believe is the Raw file I want to request. But, the Typescript below, I try using is something like this:
getTheFile(download_url: string): Observable<MyFile> {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({ headers: headers });
return this._http.get(download_url)
.map((response: Response) => {
console.log(response.text());
return null;
})
.catch(e => {
if (e.status === 401) {
return Observable.throw('Unauthorized');
}
if (e.status === 404) {
return Observable.throw('Not found.');
}
});
}
... and it fails. How can I retrieve the actual file, and parse it to an object?

Angular 2 Get request error response,

I need to send POST request to the API and if response code == 400 get info from response.
http://joxi.ru/l2ZM0KES0M8ZmJ
public contactUsSendPost(params): Observable<{}> {
return this.contactUsSendPostWithHttpInfo(params)
.map((response: Response) => response.json());
}
public contactUsSendPostWithHttpInfo(params): Observable<Response> {
const path = this.basePath + `/contact-us/send`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON());
let formParams = new URLSearchParams();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
headers.set('Accept', 'application/json');
if (params.email !== undefined) {
formParams.set('email', <any>params.email);
}
if (params.fullName !== undefined) {
formParams.set('fullName', <any>params.fullName);
}
if (params.question !== undefined) {
formParams.set('question', <any>params.question);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams.toString(),
search: queryParameters
});
return this.http.request(path, requestOptions);
}
Then im trying to get response from the service, but cant get response body.
this.fqService.contactUsSendPost(formValues).subscribe(
data => console.log(data ),
err => console.log(err) <------
);
So, how can i get response body in angular 2 from http response with 400 status code ?
You just need to catch the error on your observable, see modified code below.
public contactUsSendPost(params): Observable<{}> {
return this.contactUsSendPostWithHttpInfo(params)
.map((response: Response) => response.json())
.catch(this.handleError);
}
public contactUsSendPostWithHttpInfo(params): Observable<Response> {
const path = this.basePath + `/contact-us/send`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON());
let formParams = new URLSearchParams();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
headers.set('Accept', 'application/json');
if (params.email !== undefined) {
formParams.set('email', <any>params.email);
}
if (params.fullName !== undefined) {
formParams.set('fullName', <any>params.fullName);
}
if (params.question !== undefined) {
formParams.set('question', <any>params.question);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams.toString(),
search: queryParameters
});
return this.http.request(path, requestOptions);
}
private handleError (error: Response | any) {
return Observable.throw(error.code);
}
You can upgrade to HttpClient module angular 4.3 and above application,
If you pass the entire request object as a input the http.request method you will get an complete response object.

File upload in Angular2 not working

I am trying to create a file upload functionality where an user can upload geotiff (could be of several GBs in size).
For some reason my angular code is not able to hit the api and throws 404 but I am able to upload file with Postman.
Angular Code:
fileChange(event) {
let token = localStorage.getItem('userToken');
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('files', file, file.name);
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append("Authorization", token);
let options = new RequestOptions({ headers: headers });
this.uploadInProgress = true;
this._http.post(`${this.uploadApiUrl}`, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error),
() => this.uploadInProgress = false)
}
}
API:
// POST: api/GeoTif
[HttpPost]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
return Ok(new { NoOfUploadedFileCount = files.Count, TotalFileSize =size });
}
I understand that there is an issue with the HTTP service and FormData.. you can use XMLHttpRequest to accomplish it:
fileChange(event: Event) {
this.uploadFile(event)
.subscribe(() => {
console.log('sent');
})
}
private uploadFile(event: Event) {
return Observable.create(observer => {
const token = localStorage.getItem('userToken');
const fileList = event.target.files;
if (fileList.length > 0) {
const file = fileList[0];
const formData = new FormData();
const xhr = new XMLHttpRequest();
formData.append('files', file, file.name);
this.uploadInProgress = true;
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
this.uploadInProgress = false;
}
}
xhr.open('POST', this.uploadApiUrl, true);
xhr.send(formData);
}
});
}
Add your URL with http:// (Ex: http://localhost/api/GeoTif/).
And remove the following code.
headers.append('Content-Type', 'multipart/form-data');
headers.append("Authorization", token);

How to send form data in a http post request of angular 2?

I am trying to send form data of the updated user details to the back end which node server in angular 2,However I couldn't send the form data and the server responds with status of 500,In angularjs I have done something like this,
service file
update: {
method: 'POST',
params: {
dest1: 'update'
},
transformRequest: angular.identity,
'headers': {
'Content-Type': undefined
}
}
In controller as
var fd = new FormData();
var user = {
_id: StorageFactory.getUserDetail()._id,
loc: locDetails
};
fd.append('user', angular.toJson(user));
UserService.update(fd).
$promise.then(
function(value) {
console.info(value);
updateUserDetailsInStorage();
},
function(err) {
console.error(err);
}
);
I couldn't to figure how to do this in angular 2 as angular.toJson,angular.identity and transformrequest features are not available in angular 2,
so far I have done the following in angular 2,
let fd = new FormData();
let user = {
_id: this.appManager.getUserDetail()._id,
loc: locDetails
};
fd.append('user', JSON.stringify(user));
this.userService.update(fd).subscribe((value) => {
console.log(value);
this.updateUserDetailsInStorage();
}, (err) => {
console.error(err);
});
http service file
update(body) {
console.log('update', body);
const headers = new Headers({
'Content-Type': undefined
});
const options = new RequestOptions({
headers: headers
});
return this.http.post(`${app.DOMAIN}` + 'user/update', body, options)
.map((res: Response) => {
res.json();
}).do(data => {
console.log('response', data);
})
}
I have read many posts and tried few things but so far it was unsuccessful, could anyone suggest me how to do this?
You can add headers if your server controller requires it else you can simply post it like this
let body = new FormData();
body.append('email', 'emailId');
body.append('password', 'xyz');
this.http.post(url, body);
This is a functional solution for build a POST request in Angular2, you don't need an Authorization header.
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
var body = "firstname=" + user.firstname + "&lastname=" + user.lastname + "&username=" + user.username + "&email=" + user.email + "&password=" + user.password;
return new Promise((resolve) => {
this.http.post("http://XXXXXXXXXXX/users/create", body, options).subscribe((data) => {
if (data.json()) {
resolve(data.json());
} else {
console.log("Error");
}
}
)
});
Here is the method I've used in angular 4 for uploading files....
for Ui
<input type="file"id="file"(change)="handleFileInput($event)">
and .ts file I've added this ....
handleFileInput(event) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
this.fileToUpload = files[0];
console.log(this.fileToUpload);
}
uploadFileToActivity() {
console.log('Uploading file in process...!' + this.fileToUpload );
this.fontService.upload(this.fileToUpload).subscribe(
success => {
console.log(JSON.stringify(this.fileToUpload));
console.log('Uploading file succefully...!');
console.log('Uploading file succefully...!' + JSON.stringify(success));
},
err => console.log(err),
);
}
and In services
upload(fileToUpload: File) {
const headers = new Headers({'enctype': 'multipart/form-data'});
// headers.append('Accept', 'application/json');
const options = new RequestOptions({headers: headers});
const formData: FormData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
console.log('before hist the service' + formData);
return this.http
.post(`${this.appSettings.baseUrl}/Containers/avatar/upload/`, formData , options).map(
res => {
const data = res.json();
return data;
}
).catch(this.handleError);
}
This method used for single file uploading to the server directory.
Here is the method from my app which works fine.
updateProfileInformation(user: User) {
this.userSettings.firstName = user.firstName;
this.userSettings.lastName = user.lastName;
this.userSettings.dob = user.dob;
var headers = new Headers();
headers.append('Content-Type', this.constants.jsonContentType);
var s = localStorage.getItem("accessToken");
headers.append("Authorization", "Bearer " + s);
var body = JSON.stringify(this.userSettings);
return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
.map((response: Response) => {
var result = response.json();
return result;
})
.catch(this.handleError)
}
FINAL answer
sending like below working fine .
const input = new FormData();
input['payload'] = JSON.stringify(param);
console.log(input);
alert(input);
return this.httpClient.post(this.hostnameService.razor + 'pipelines/' +
workflowId, input).subscribe(value => {
console.log('response for Manual Pipeline ' + value);
return value;
}, err => {
console.log(err);
});

Categories