Post image/file (multipart) with Angular6 - json

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 ?

Related

SyntaxError: Unexpected token S in JSON at position 0 at JSON.parse

I'm trying to remove message notification. but this error appear "SyntaxError: Unexpected token S in JSON at position 0 at JSON.parse" , is there any relation with the type defined in the headers? How can i resolve this error?
Front-End Angular 12
public removeNotificationForUser(onlineUserModel: OnlineUserModel) {
let targetUsername = onlineUserModel.userName;
const url_ = `${this.baseUrlRemoveNotifications}?targetUsername=${targetUsername}`;
const url = this.baseUrlRemoveNotifications + "/" + targetUsername;
const body = {};
const options = {
headers: new HttpHeaders({
"Content-Type": "application/json",
"X-XSRF-TOKEN": this.cookieService.get("XSRF-TOKEN"),
}),
};
return this.http.patch<any>(url_, body, options).subscribe(
(val) => {
console.log("PATCH call successful value returned in body", val);
},
(response) => {
console.log("PATCH call in error", response);
},
() => {
console.log("The PATCH observable is now completed.");
}
);
}
Back-End Asp.net Core
[HttpPatch("[action]/{targetUsername}")]
[Route("removeNotifications")]
public async Task<IActionResult> RemoveNotifications( [FromQuery] string targetUsername)
{
try
{
var sender = await _userManager.FindByNameAsync(targetUsername);
var reciever = await _userManager.FindByNameAsync(User.Identity.Name);
// Find The Connection
var RecieverResetNotification= _userInfoInMemory.GetUserInfo(User.Identity.Name);
var SenderResetNotification = _userInfoInMemory.GetUserInfo(targetUsername);
var notificationToBeRemoved = _context.Notifications.Where(N => ((N.ReceiverId == reciever.Id) && (N.SenderId == sender.Id) && (N.IsSeen == false))).ToList();
//Send My reset notification to the the others sessions :
var mySessions = _context.Connections.Where(C => ((C.ConnectionID != RecieverResetNotification.ConnectionID) && (C.Username == reciever.UserName) && (C.Connected == true))).Select(MyCID => MyCID.ConnectionID).ToList();
if (mySessions != null)
{
await _hubContext.Clients.Clients(mySessions).SendAsync("MyResetNotification", RecieverResetNotification);
}
//Test if notificationToBeRemoved
if (notificationToBeRemoved != null)
{
notificationToBeRemoved.ForEach(NR => NR.IsSeen = true);
_context.SaveChanges();
}
// My Methode to update Notification Table => change Iseen column to true //
return Ok("Success");
}
catch (Exception ex)
{
Log.Error("An error occurred while seeding the database {Error} {StackTrace} {InnerException} {Source}",
ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
}
return BadRequest("Failed");
}

Deno post method empty request body

I am currently developing a proof-of-concept REST api app with Deno and I have a problem with my post method (getAll et get working). The body of my request does not contain data sent with Insomnia.
My method :
addQuote: async ({ request, response }: { request: any; response: any }) => {
const body = await request.body();
if (!request.hasBody) {
response.status = 400;
response.body = { message: "No data provided" };
return;
}
let newQuote: Quote = {
id: v4.generate(),
philosophy: body.value.philosophy,
author: body.value.author,
quote: body.value.quote,
};
quotes.push(newQuote);
response.body = newQuote;
},
Request :
Response :
I put Content-Type - application/json in the header.
If I return only body.value, it's empty.
Thanks for help !
Since value type is promise we have to resolve before accessing value.
Try this:
addQuote: async ({ request, response }: { request: any; response: any }) => {
const body = await request.body(); //Returns { type: "json", value: Promise { <pending> } }
if (!request.hasBody) {
response.status = 400;
response.body = { message: "No data provided" };
return;
}
const values = await body.value;
let newQuote: Quote = {
id: v4.generate(),
philosophy: values.philosophy,
author: values.author,
quote: values.quote,
};
quotes.push(newQuote);
response.body = newQuote;
}

Angular 6 - get csv response from httpClient

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.

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

Convert Promise object to JSON in Angular 2

I'm trying to make an HTTP POST and then check the response to see if it fails or succeeds.
The HTTP call looks like this :
doLogin(credentials) {
var header = new Headers();
header.append('Content-Type', 'application/x-www-form-urlencoded');
var body = 'username=' + credentials.username + '&password=' + credentials.password;
return new Promise((resolve, reject) => {
this.http.post(this.url, body, {
headers: header
})
.subscribe(
data => {
resolve(data.json());
},
error => {
resolve(error.json());
}
);
});
}
And the call of this function is the following :
data: Object;
errorMessage: Object;
login($event, username, password) {
this.credentials = {
username: username,
password: password
};
this._loginService.doLogin(this.credentials).then(
result => {
this.data = result;
console.log(this.data);
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
});
}
On Chrome console, the data is the following :
Object {status: "Login success", token: "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjcmlzdGkiLCJ1c2VyS…blf1AzZ6KzRWQFNGXCrIeUHRG3Wrk7ZfCou135WmbVa15iYTA"}
How can I access the status in Angular 2? Because if I'm trying to access this.data.status, it's not working.
Should I create a class with the status and token properties?
To answer your question, you can use the response.okboolean that's available in the subscription of the observable from the http.
So based on your code you could pass the data object straight to the promise and inspect data.ok before parsing the data.json.
//...
return new Promise((resolve, reject) => {
this.http.post(this.url, body, {
headers: header
})
.subscribe(resolve,
error => {
reject(error.json());
}
);
});
// then you would have something like this:
this._loginService.doLogin(this.credentials).then(
result => {
if (result.ok) {
this.data = result;
console.log(this.data);
}
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
})
SUGGESTION
Now, I would recommend getting rid of the promise, as I believe you don't really need it. whoever is consuming your service can just subscribe to the observable returned by the http post, like so:
doLogin(credentials) {
let header = new Headers();
header.append('Content-Type', 'application/x-www-form-urlencoded');
var body = 'username='+credentials.username+'&password='+credentials.password;
return this.http.post(this.url, body, { headers: header });
}
Then, when logging in:
login($event, username, password) {
this.credentials = {
username: username,
password: password
};
this._loginService.doLogin(this.credentials).subscribe(response => {
if (response.ok) { // <== CHECK Response status
this.data = response.json();
console.log(this.data);
} else {
// handle bad request
}
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
});
}
Hope this helps!
You could do it like this:
data: Object;
errorMessage: Object;
login($event, username, password) {
this.credentials = {
username: username,
password: password
};
this._loginService.doLogin(this.credentials).then(
(result: any) => {
this.data = result;
console.log(this.data);
console.log(this.data.status);
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
});
}
Set the result to type any. That way you'll be able to access the status, however you could create a class and use rxjs/map within your service to populate the class if you so desire.