Angular 6 - get csv response from httpClient - html

Can any one please give an example of fetching application/octet-stream response from angular 6 httpClient. I am using the below code and it doesn't work ( I get unknown error - 401 response) -
import { saveAs } from 'file-saver';
getJobOutput() {
this.workflowService.fetchOutput(this.jobId,this.outputId).subscribe((response : any) => { // download file
var blob = new Blob([response.blob()], {type: 'application/octet-stream'});
var filename = 'file.csv';
saveAs(blob, filename);
});
}
Service is as below -
fetchOutput(jobId : string, outputId) {
var jobOutputURL = "myEnpoint";
var params = this.createHttpAuthorization(jobOutputURL,"GET");
params["format"] = "csv";
const options = {
headers: new HttpHeaders( { 'Content-Type': 'application/octet-stream',
'Accept' : 'application/octet-stream',
'Access-Control-Allow-Origin' : '*'}
)};
var endpoint = `${jobOutputURL}?oauth_consumer_key=${params["oauth_consumer_key"]}&oauth_signature_method=${params["oauth_signature_method"]}&oauth_nonce=${params["oauth_nonce"]}&oauth_timestamp=${params["oauth_timestamp"]}&oauth_version=1.0&format=${params["format"]}&oauth_signature=${params["oauth_signature"]}`;
return this.httpClient.get(endpoint, {...options, responseType: 'blob'});
}

To fetch an application/octet-stream, you have to set arraybuffer as the response type in the Angular HttpHeaders.
This is the service method:
fetchOutput(): Observable<ArrayBuffer> {
let headers = new HttpHeaders();
const options: {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
} = {
responseType: 'arraybuffer'
};
return this.httpClient
.get('https://your-service-url.com/api/v1/your-resource', options)
.pipe(
map((file: ArrayBuffer) => {
return file;
})
);
}
This is the call to the service method and to the saveAs function:
this.yourService
.fetchOutput()
.subscribe((data: any) => {
const blob = new Blob([data], { type: 'application/octet-stream' });
const fileName = 'Your File Name.csv';
saveAs(blob, fileName);
})
As other users are suggestion: 401 Unauthorized is usually a client side error due to missing credentials.

Related

Unable to show blob url in "pdf-viewer" => "ng2-pdf-viewer" in Angular 10

I have an API which is returning uploaded file as blob. When I try to bind src with blob URL then it does not show anything, however, when I try to bind direct URL then it can show PDF file. Here is my code given below.
My TS code
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
},
(err: Error) => {
},
() => {
const blob: Blob = new Blob([this.tempBlob], { type: this.contentType });
const fileName: string ='ilvsna.pdf';
this.myBlobURL = URL.createObjectURL(blob);
}
);
}
HTML
<pdf-viewer [src]="myBlobURL"
[render-text]="true"
[original-size]="false"
style="width: 400px; height: 500px"
></pdf-viewer>
Note: if I set myBlobURL URL to 'https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf' then it can display
I think I have a solution for you. You can use ArrayBuffer. #N.F. Code is correct, however, you said that you got error in the line => this.pdfSrc = new Uint8Array(fileReader.result);
So, change the line into => this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);.Finally, your ts code should look like below=>
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
const fileReader = new FileReader();
fileReader.onload = () => {
this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);
};
fileReader.readAsArrayBuffer(this.tempBlob);
},
(err: Error) => {
}
);
}
Try this.
ts
pdfSrc: Uint8Array;
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
const fileReader = new FileReader();
fileReader.onload = () => {
this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);
};
fileReader.readAsArrayBuffer(this.tempBlob);
},
(err: Error) => {
}
);
}
html
<pdf-viewer [src]="pdfSrc"
[render-text]="true"
[original-size]="false"
style="width: 400px; height: 500px"
></pdf-viewer>
I resolve with window.URL.createObjectURL of my return blob file from service:
-- ts file
this.obuService.getObuDocument(obuId, fileId).subscribe(
(data: HttpResponse<Blob>) => {
const url = window.URL.createObjectURL(data.body);
this.src = url;
this.viewPDF = true;
}
);
-- service
getObuDocument(obuId: number, fileId: number): Observable<any> {
const options = {
observe: 'response' as 'body',
Accept: 'application/pdf',
responseType: 'blob' as 'blob'
};
return this.http.get(this.apiUrl + '/' + obuId + '/upload/' + fileId, options)
.pipe(catchError(err => { throw err; }));
}

how to fetch large json from a post in angular6/7

I have migrated a piece of code to be able to export data as excel file in angular.
I assume the fact that the json is well formed and send from the server to the angular side. I can see it in the network frame in th browser.
For small json, it's ok but when the size of the json starts to be large, the answer still failed.
This following code corresponding to the service call
exportSynthesis(recordId: number, moduleId: number) {
const body = null;
return this.http.post(this.apiUrl + `/data`
+ `${recordId}/module/${moduleId}`, body,
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response', responseType: 'json' }).pipe(
map((resp: any) => {
return resp.body;
}));
}
and here, its the method which manages the return.
exportSynthesis() {
this.service.exportSynthesis(this.recordId, this.moduleId)
.subscribe(
(exportResult) => { this.exportResult = exportResult; },
err => {
console.log('err:', err);
this.errorHandlerService.handleError('failed', err);
},
() => {
console.log('json:', this.exportResult);
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.exportResult);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '(GEO) ' + this.record.label + ' - name.xlsx';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
});
}
Currently, i do not manage to understand why it still finish in error and I get only "ok" in the console log.
Any idea?
regards
Angular's HttpClientModule default response is a json.
Your problem is that you try to access the body property of the HTTP response, but Angular interprets that as you trying to access the body property in the body of the response.
Remove observe and responseType from your post request and treat the response as a json. It should work.
find:
just need to use text as json
return this.http.post(this.apiUrl + `/geo/v1/synthesis/xls/record/`
+ `${recordId}/module/${moduleId}`, body,
{
headers: headers,
observe: 'response',
responseType: 'text' as 'json'}).
map((resp: any) => {
return resp.body;
});
}

Post image/file (multipart) with Angular6

I try to post an image with http.post from Angular6.
See below my rest service and component.
Service
setOptions(data: boolean = false, headersToSet?: any): any {
let token: string;
const headers = [];
token = JSON.parse(localStorage.getItem('SOSF_MANAGER_TOKEN'));
// AUTHORIZATION
headers['Authorization'] = 'Bearer ' + token;
headers['Content-Type'] = data ? 'multipart/form-data' : 'application/json';
// OTHER HEADERS
if (headersToSet !== undefined) {
for (const headerName of Object.keys(headersToSet)) {
headers[headerName] = headersToSet[headerName];
}
}
return { headers };
}
// POST
postDb(url: string, body: any): Observable<any> {
let options: any;
options = this.setOptions(body instanceof FormData);
url = this.url + url;
if (!(body instanceof FormData)) {
body = JSON.stringify(body);
} else {
// TO DO
}
console.log(body);
if (environment.console_log_construct) {
console.log(`POST : ${url}`);
}
return this.http.post(url, body, options).pipe(
map(response => {
return response;
}, error => {
console.error(`POST ERROR: ${url}`, error);
}));
}
Component
// Open Our formData Object
const formData = new FormData();
// Append our file to the formData object
formData.append('file', files[0]);
// POST
this.restService.postDb('files/images', formData)
.subscribe(response => {});
If I let JSON.stringify(body) when body is formData, formdata is set to {}. But if I let body like this, it throw a error 'Uncaught SyntaxError: Unexpected token o in JSON at position 1'. How can I achieve it ?

Delete Objects in Bucket with jQuery

How do i selete an object in a bucket through a jQuery-Call. The following Code shows my example for uploading the file. The goal is to have the deleting in a similar way. Thanks
function uploadFile(node) {
$('#hiddenUploadField').click();
$('#hiddenUploadField').change(function () {
if (this.files.length == 0) return;
var file = this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
}
});
break;
}
});
}
You could expose the necessary part on the server side (just like it is done for the /api/forge/oss/objects endpoint which uploads a file to a given bucket) which then could be called from the client side in a similar way.
Server side:
router.delete('/buckets/:id', function (req, res) {
var tokenSession = new token(req.session)
var id = req.params.id
var buckets = new forgeSDK.BucketsApi();
buckets.deleteBucket(id, tokenSession.getOAuth(), tokenSession.getCredentials())
.then(function (data) {
res.json({ status: "success" })
})
.catch(function (error) {
res.status(error.statusCode).end(error.statusMessage);
})
})
Client side:
function deleteBucket(id) {
console.log("Delete bucket = " + id);
$.ajax({
url: '/dm/buckets/' + encodeURIComponent(id),
type: 'DELETE'
}).done(function (data) {
console.log(data);
if (data.status === 'success') {
$('#forgeFiles').jstree(true).refresh()
showProgress("Bucket deleted", "success")
}
}).fail(function(err) {
console.log('DELETE /dm/buckets/ call failed\n' + err.statusText);
});
}
Have a look at this sample which has both file upload and bucket deletion implemented: https://github.com/adamenagy/oss.manager-nodejs
Ah great, thank you. And how would you solve it on the server side with C# ? Rigth now the Upload on server-side looks like:
[HttpPost]
[Route("api/forge/oss/objects")]
public async Task<dynamic> UploadObject()
{
// basic input validation
HttpRequest req = HttpContext.Current.Request;
if (string.IsNullOrWhiteSpace(req.Params["bucketKey"]))
throw new System.Exception("BucketKey parameter was not provided.");
if (req.Files.Count != 1)
throw new System.Exception("Missing file to upload");
string bucketKey = req.Params["bucketKey"];
HttpPostedFile file = req.Files[0];
// save the file on the server
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"),
file.FileName);
file.SaveAs(fileSavePath);
// get the bucket...
dynamic oauth = await OAuthController.GetInternalAsync();
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
// upload the file/object, which will create a new object
dynamic uploadedObj;
using (StreamReader streamReader = new StreamReader(fileSavePath))
{
uploadedObj = await objects.UploadObjectAsync(bucketKey,file.FileName,
(int)streamReader.BaseStream.Length, streamReader.BaseStream,"application/octet-
stream");
}
// cleanup
File.Delete(fileSavePath);
return uploadedObj;
}

Not able to download OBJ file using GetDerivativeManifest

I am trying to download an OBJ file generated from SVF file, using the Autodesk.Forge .NET API method GetDerivativeManifest (C#). The OBJ file has been created successfully. However, the method does not provide a Stream that I can use to retrieve the file and save it locally.
How can I get the OBJ file?
I don't have a C# sample ready to give you, but I hit the same issue with the Node.js SDK. I worked around by implementing the REST call myself:
download (token, urn, derivativeURN, opts = {}) {
// TODO SDK KO
//this._APIAuth.accessToken = token
//
//return this._derivativesAPI.getDerivativeManifest(
// urn,
// derivativeURN,
// opts)
return new Promise((resolve, reject) => {
const url =
`${DerivativeSvc.SERVICE_BASE_URL}/designdata/` +
`${encodeURIComponent(urn)}/manifest/` +
`${encodeURIComponent(derivativeURN)}`
request({
url: url,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token.access_token
},
encoding: null
}, function(err, response, body) {
try {
if (err) {
return reject(err)
}
if (response && [200, 201, 202].indexOf(
response.statusCode) < 0) {
return reject(response.statusMessage)
}
if (opts.base64) {
resolve(bufferToBase64(body))
} else {
resolve(body)
}
} catch(ex) {
console.log(ex)
reject(ex)
}
})
})
}
Here is how I invoke that method within my endpoint:
/////////////////////////////////////////////////////////
// GET /download
// Download derivative resource
//
/////////////////////////////////////////////////////////
router.get('/download', async (req, res) => {
try {
const filename = req.query.filename || 'download'
const derivativeUrn = req.query.derivativeUrn
// return base64 encoded for thumbnails
const base64 = req.query.base64
const urn = req.query.urn
const forgeSvc = ServiceManager.getService(
'ForgeSvc')
const token = await forgeSvc.get2LeggedToken()
const derivativesSvc = ServiceManager.getService(
'DerivativesSvc')
const response = await derivativesSvc.download(
token, urn, derivativeUrn, {
base64: base64
})
res.set('Content-Type', 'application/octet-stream')
res.set('Content-Disposition',
`attachment filename="${filename}"`)
res.end(response)
} catch (ex) {
res.status(ex.statusCode || 500)
res.json(ex)
}
})
Hope that helps