I am consuming some larger API endpoints (the returned JSON response is about 10MB).
Is there a way with http.request or fetch to get notifications about the "download" status.
Nicky
You could use this npm package nativescript-background-http
Here is an example for how to track the progress:
var bghttp = require("nativescript-background-http");
var session = bghttp.session("image-upload");
var request = {
url: "http://myserver.com",
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"File-Name": "bigpig.jpg"
},
description: "{ 'uploading': 'bigpig.jpg' }"
};
var task = session.uploadFile("file/path/bigpig.jpg", request);
task.on("progress", logEvent);
task.on("error", logEvent);
task.on("complete", logEvent);
function logEvent(e) {
console.log(e.eventName);
}
Related
I am writing API tests using Cypress 6.4.0 & TypeScript where I need to upload a pdf file in the request body.
My code for the request is:
My code for the request body is:
public async createAssetDocTest() {
let url = sharedData.createAsset_url + sharedData.assetA;
let response = await fetch(url
,
{
method: 'POST',
body: await requestbody.createAssetDocBody(),
headers: {
Authorization: sharedData.bearer + " " + adminTokenValue,
Accept: sharedData.accept,
'Content-type': sharedData.docReqContent,
},
}
);
expect(response.status).to.equal(200);
public async createAssetDocBody(): Promise<any> {
const file = sharedData.doc;
cy.fixture(file).then((pdfDoc) => {
Cypress.Blob.binaryStringToBlob(
pdfDoc,
sharedData.contentTypeValue
).then(async (blob: string | Blob) => {
const formData = new FormData();
formData.set(sharedData.document, blob, file);
const body = {
formdata: {
document: {
value: pdfDoc,
options: {
filename: sharedData.document,
contentType: null,
},
},
},
};
return body;
});
});
}
However, the file does not upload the file & the request fails with error 400. Is there a better way to upload files in the body of the POST request?
enter image description here
Resolved this issue!
The main issue was that my Cypress version was too old. Upgraded to 9.7.0
Then added the following code:
public async createAssetDoc(): Promise<any> {
cy.fixture("pic location", "binary")
.then((file) => Cypress.Blob.binaryStringToBlob(file))
.then((blob) => {
var formdata = new FormData();
formdata.append("document", blob, "pic location");
const url = "your url";
cy.request({
url,
method: "POST",
body: formdata,
headers: {
Authorization:
"bearer" + " " + token,
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
}).then((response) => {
expect(response.status).to.equal(201);
expect(response.statusText).to.equal(
sharedData.fileUploadStatusText
);
const finalResponse = String.fromCharCode.apply(
null,
new Uint8Array(response.body)
);
return finalResponse;
});
});
}
I have the following test
let rxId = "";
let basketAuthToken = "";
let basketId = "";
let replacedBody = "";
cy.fixture(`payload/${ordersPostPayload}`).then((Body) => {
cy.readFile(`temp/resultIdFile.json`).then((resultIdFile) => {
Id = resultIdFile.lastSucceededRxId;
basketAuthToken = resultIdFile.baskets[0].authToken;
basketId = resultIdFile.baskets[0].basketId;
cy.log(`the value of the read value is ${Id}`);
replacedBody = JSON.stringify(Body).split(`$Id`).join(Id);
cy.writeFile(`temp/ordersPostPayload.json`, replacedBody);
cy.request({
method: "POST",
url: `https://***/ops/orders`,
headers: {
"Content-Type": "application/json",
Channel: "**",
"EsbApi-Subscription-Key": `****`,
"Accept-Language": `en-US`,
"basket-token": basketAuthToken,
"basket-id": basketId,
redirectUrl: "****/evaluate-payment",
cancelUrl: "****/evaluate-payment",
},
body: replacedBody,
failOnStatusCode: false,
}).then((response) => {
cy.writeFile("temp/result.json", response);
});
});
});
The request is sent to the backend. On cypress GUI the request is just fired once. but when I check the backend I can see two requests.
i have some troubles with imgur api. I converted image to base64 code and tried upload it to imgur api. Unfortuatelly I'm receiving an error:
"error": "Invalid URL (data:image/png;base64,iVBORw0KGgoAA..."
Here's my function:
uploadImageToImgur: function (file) {
const url = 'https://api.imgur.com/3/image',
reader = new FileReader();
reader.onloadend = async function () {
let { result } = reader;
try {
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'my client key',
},
body: result
});
const response = await request.json();
console.log(response);
} catch (e) {
throw new Error(e);
}
}
if (file) {
reader.readAsDataURL(file);
}
}
You need to cut this part out.
You are missing some parameters. Also, make sure your headers have the Client-ID key.
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'Client-ID {yourKey}',
},
form: {
"image": result,
"type": "base64"
}
});
I would like to return the response body text returned by the POST that I send by fetch.
var r = '';
var res = fetch(this.commentsUrl, {
method: 'post',
body: JSON.stringify(comment),
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
return response.text().then(function (text) {
r = text;
})
});
Neither r or res is returning the body text. They are both returning Promise. How do I only return the body text?
I was able to get the response body text by using await.
const response = await fetch(this.commentsUrl, {
method: 'post',
body: JSON.stringify(comment),
headers: {
'Content-Type': 'application/json'
}
});
const text = await response.text();
I am currently using nativescript-background-http to upload images and I was just wondering is there a way to get the response body or response header coming from the server after sending the image?
Just in case someone has the same problem a year later:
task.on("responded", (e) => {
JSON.parse(e.data)
}
The way I was able to get the response back from the server was in the complete method use the getBodyAsString() method and parse it.
task.on("complete", (ev: any) => {
console.log("Upload complete");
let sr = JSON.parse(ev.response.getBodyAsString());
});
function sendImages(uri, fileUri) {
imageName = extractImageName(fileUri);
var request = {
url: "http://httpbin.org/post",
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"File-Name": imageName
},
description: "{ 'uploading': " + imageName + " }"
};
var task = session.uploadFile(fileUri, request);
task.on("progress", logEvent);
task.on("error", logEvent);
task.on("complete", logEvent);
function logEvent(e) {
console.log("----------------");
console.log('Status: ' + e.eventName);
// console.log(e.object);
if (e.totalBytes !== undefined) {
console.log('current bytes transfered: ' + e.currentBytes);
console.log('Total bytes to transfer: ' + e.totalBytes);
}
}
return task;
}
Based on this demo