OneDrive Upload API, resumeable uploading does not work on web - onedrive

I have developed web apps. http://onedrive.booogle.net/
The resumeable uploading for OneDrive API does not work on web. Simple
item uploading only works (100M limit). "Request header field
Content-Range is not allowed by Access-Control-Allow-Headers."
error occurs on Chrome, Firefox...
Is it bugs? How to fix it?
function _upload_send(uploadUrl){
var cfiledata='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var body=btoa(cfiledata);
var start=0;
var end=cfiledata.length;
var len=cfiledata.length;
xhr.open('PUT', uploadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + md_access_token);
xhr.setRequestHeader('Content-Range', 'bytes '+start+'-'+(end-1)+'/'+len);
xhr.setRequestHeader('Content-Encoding', 'base64');
xhr.onload = function(){
//Request header field Content-Range is not allowed by Access-Control-Allow-Headers.
};
xhr.onerror = function(e){
//Request header field Content-Range is not allowed by Access-Control-Allow-Headers.
};
xhr.send(body);
}
function _upload_create(){
filename='largefile.txt';
xhr.open('POST', 'https://api.onedrive.com/v1.0'+'/drive/items/'+upload_id+':/'+encodeURIComponent(filename)+':/upload.createSession');
xhr.setRequestHeader('Authorization', 'Bearer ' + md_access_token);
xhr.setRequestHeader('Content-Type', 'application/json');
var body={
"item": {
"#name.conflictBehavior": "rename",
"name": filename
}
};
xhr.onload = function(){
if(this.status==200){
try{
var a=JSON.parse(this.response);
if(a.uploadUrl){
_upload_send(a.uploadUrl);
}
}catch(err){}
}
};
xhr.onerror = function(e){
};
xhr.send(JSON.stringify(body));
}

This is a bug. Thanks for reporting it. Tracking with https://github.com/OneDrive/onedrive-api-docs/issues/157. We'll fix it soon.
-- update --
This is now fixed.

Related

Shutdown Kodi with api (blackberry qml)

Hello I trying shutdown Kodi (raspberry pi) with mobile app (blackberry qml).
But I do not how.
I used this code: (in browser)
"http://[myip]:[myport]/jsonrpc?request={"jsonrpc":"2.0","method":"System.Suspend","id":1}"
I used this code: (in the app)
function sendRequest() {
var xhr = new XMLHttpRequest();
var url = "http://[myip]:[myport]/jsonrpc?request={\"jsonrpc\":\"2.0\",\"method\": \"System.Suspend\",\"id\":1}"
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
textArea.text = xhr.responseText;
}
}
};
xhr.open("GET", url, true); // with "POST" I got the same problem.
xhr.send();
}
I got:
{"error":{"code":-32700,"message":"Parse error."},"id":null,"jsonrpc":"2.0"}
Remote from web browser works fine (http://[myip]:[myport])
Thank you for your answers.
********** Update: 21.10.2020 **********
I'm in progress. But I don't know what to do next.
I found some information why I have an error.
I don't know how to implement in my code.
Can you help me?
Thank you so much.
https://github.com/xbmc/xbmc/pull/12281
https://forum.kodi.tv/showthread.php?tid=324598&highlight=json
Here's how to do it.But I can't understand it.
https://retifrav.github.io/blog/2018/09/01/kodi-remote-control-app/
This is my function (on Kodi 17.6 it is working but on Kodi 18 is not working )
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
text.text = xhr.responseText
}
}
};
var url = 'http://<IP:PORT>/jsonrpc?request={"jsonrpc": "2.0", "id": 1, "method": "System.Shutdown"}'
xhr.open("GET", url, true) // when I write "POST" - nothing happens
xhr.send()
}
You should URL encode the json in your url before it's used in the open method. Use encodeURIComponent() to do that. Your browser is changing:
{"jsonrpc":"2.0","method": "System.Suspend","id":1}"
To:
%7B%22jsonrpc%22%3A%222.0%22%2C%22method%22%3A%20%22System.Suspend%22%2C%22id%22%3A1%7D%22
But your code is not.

Imgur can't upload "message": "Failed stripping metadata"

I'm making an api getting a gif that uploads it to imgur,
but when requesting the api (express or postman),
i receive an error (everything works fine with other pictures):
{
data: {
error: {
code: 1001,
message: "Failed stripping metadata",
type: "Exception_Logged",
exception: {}
},
request: "/3/upload",
method: "POST"
},
success: false,
status: 500
}
How to avoid this error ? How to correct this picture ? "Adding metadata ?"
Is it due to the fact the picture was saved with ffmpeg ?
When i upload with the imgur pannel, everyting is fine,but not with the api
Thanks
https://imgur.com/xn4iG08
Note: i suppose the medata were removed by imgur, but I only can give that, thank you so much
I just ran into this issue. In my case the cause was the wrong encoding of the data in image parameter, it needs to be URL encoded (i.e. by using encodeURIComponent()).
My code uploads the contents of a Canvas object in PNG format and looks like this:
function encode(x)
{
return encodeURIComponent(x.substring(x.indexOf(",") + 1));
}
let xhr = new XMLHttpRequest();
xhr.onload = function(e) { console.log(e); };
xhr.onerror = function(e) { console.log(e); };
xhr.open("POST", "https://api.imgur.com/3/image");
xhr.setRequestHeader("Authorization", "Client-ID <your client id here>");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("image=" + encode(canvas.toDataURL()));

Multipart formdata POST request just doesn't work in Cypress for me

Nothing works for me. If I use cy.request(), I'm unable to send formdata with it which contains a text and an image. So I've to go via XHR route. So, in my command.js I've used the following code to create a command: -
Cypress.Commands.add("formrequest", (method, url, formData, done) => {
cy.window().then(win => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url, false);
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("access-token", accesstoken);
xhr.setRequestHeader("client", client);
xhr.setRequestHeader("expiry", expiry);
xhr.setRequestHeader("token-type", tokentype);
xhr.setRequestHeader("uid", uid);
xhr.setRequestHeader("Accept-Encoding", null);
xhr.onload = function() {
done(xhr);
};
xhr.onerror = function() {
done(xhr);
};
xhr.send(formData);
});
});
});
Now, when I'm calling it I will first construct a BLOB and then use it in my formdata to later send the XHR request. Like this: -
it.only("Test XHR", () => {
cy.AppLogin();
cy.fixture("/images/clients/Golden JPEG.jpeg", "binary").then(imageBin => {
// File in binary format gets converted to blob so it can be sent as Form data
Cypress.Blob.binaryStringToBlob(imageBin, "image/jpeg").then(blob => {
// Build up the form
const formData = new FormData();
formData.set("client[name]", "Test TER"); //adding a plain input to the form
formData.set(
"client[client_logo_attributes][content]",
blob
//"Bull Client.jpg"
); //adding a file to the form
// Perform the request
cy.formrequest(method, url, formData, function(response) {
expect(response.status).to.eq(201);
});
});
});
});
Please note that cy.AppLogin() sets up the request headers like accesstoken, client, expiry, tokentype and uid.
Kindly refer to the attached file (XHRfromCypress.txt) for checking the XHR request being generated using the code provided above. Also attached is a file (XHRfromCypressUI.txt) for showing XHR request being made when I did run my cypress end-2-end test from application UI.
I'm constantly getting 405, Method not allowed error.
E2E test from UI
API Test
E2E test works but API test using above code simply doesn't work. I also tried cy.request() but as it is not shown in the developers tab I'm not sure I've done it correctly. Also, i'm doubtful about the way I used formdata in there. Means whether cy.request() can even accept dormdata.
I've both (E2E and API) XHR's exported, just in case those are needed.
Do I need to add any libraries to make XHR request? I've aonly added Cypress library in my project setup.
////////////////
Moving all code into Test Case neither fixes anything
it.only("POSTing", () => {
cy.fixture("/images/clients/Golden JPEG.jpeg", "binary").then(imageBin => {
Cypress.Blob.binaryStringToBlob(imageBin, "image/jpeg").then(blob => {
data.set("client[name]", "Test TER fails");
data.set("client[client_logo_attributes][content]", blob);
xhr.open(method, url);
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("access-token", accesstoken);
xhr.setRequestHeader("client", client);
xhr.setRequestHeader("expiry", expiry);
xhr.setRequestHeader("token-type", tokentype);
xhr.setRequestHeader("uid", uid);
xhr.send(data);
});
});
});
You can send multi form data with cy.request.
function (imagePath, imageType, attr1, attr2, attr1Val, done) => {
cy.fixture(imagePath, "binary").then(imageBin => {
Cypress.Blob.binaryStringToBlob(imageBin, imageType).then(blob => {
const data = new FormData();
data.set(attr1, attr1Val);
data.set(attr2, blob);
cy.request({
method: "POST",
url: "https://api.teamapp.myhelpling.com/admin/clients",
headers: {
accept: "application/json",
access-token: accesstoken,
client: client,
expiry: expiry,
token-type, tokentype,
uid: uid
},
body: data
}).then((res) => {
done(res);
});
});
});
}
An improvement to the solution would be to use aliases for the async operations.
Then you can directly return the request promise and do the test evaluation in your test case.
Thanks Eric. It works for me following Eric's advise and instructions mentioned at github.com/javieraviles/cypress-upload-file-post-form
Cypress.Commands.add(
"Post_Clients",
(imagePath, imageType, attr1, attr2, attr1Val, done) => {
cy.fixture(imagePath, "binary").then(imageBin => {
Cypress.Blob.binaryStringToBlob(imageBin, imageType).then(blob => {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
const data = new FormData();
data.set(attr1, attr1Val);
data.set(attr2, blob);
xhr.open("POST", "https://api.teamapp.myhelpling.com/admin/clients");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("access-token", accesstoken);
xhr.setRequestHeader("client", client);
xhr.setRequestHeader("expiry", expiry);
xhr.setRequestHeader("token-type", tokentype);
xhr.setRequestHeader("uid", uid);
xhr.onload = function() {
done(xhr);
};
xhr.onerror = function() {
done(xhr);
};
xhr.send(data);
});
});
}
);
it.only("API POSTing TEST", () => {
cy.Post_Clients(
"/images/clients/Golden JPEG.jpeg",
"image/jpeg",
"client[name]",
"client[client_logo_attributes][content]",
"Test Attr 1 Value is Hi!!!",
response => {
cy.writeFile(
"cypress/fixtures/POST API OUTPUT DATA/Client.json",
response.
);
expect(response.status).to.eq(201);
}
);
});

how to download a pdf file from an url in angular 5

I currently spend one day in this issue,still failed to download a file from an url in angular 5
leadGenSubmit() {
return this.http.get('http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf',
{responseType:ResponseContentType.Blob}).subscribe((data)=>{
console.log(data);
var blob = new Blob([data], {type: 'application/pdf'});
console.log(blob);
saveAs(blob, "testData.pdf");
},
err=>{
console.log(err);
}
)
}
when I run above code it shows following error
ERROR TypeError: req.responseType.toLowerCase is not a function
at Observable.eval [as _subscribe] (http.js:2187)
at Observable._trySubscribe (Observable.js:172)
how can I solve this issue.Can any one post the correct code to download a pdf file from an url in angular 5?
I think you should define header and responseType like this:
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.http.get(url, { headers: headers, responseType: 'blob' });
Here is my simple solution to open a PDF based on an ID in Angular :
In my service, I created this method :
public findById(id?: string): Observable<Blob> {
return this.httpClient.get(`${this.basePath}/document/${id}`, {responseType: 'blob'});
}
Then in my component, I can do use this method (behind a button or whatever):
showDocument(documentId: string): void {
this.yourSuperService.findById(documentId)
.subscribe((blob: Blob): void => {
const file = new Blob([blob], {type: 'application/pdf'});
const fileURL = URL.createObjectURL(file);
window.open(fileURL, '_blank', 'width=1000, height=800');
});
}
Try this
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.http.get(url, { headers: headers, responseType: 'blob' as 'json' });
References:
Discussion on Angular Github
Stackoverflow

The request sent by jQuery or JavaScript doesn't contain the Header so I received error 405

I have the HTML file and try to send the request from that page with JavaScript or jQuery, but it doesn't send the "header" to the server and it gives me the error 405. I've read related questions and try out some of them but the error code was the same. I use Fiddler to see the final request and in that there is no header as well as the method change to the OPTION!
some of the codes I used:
$.ajax({
url: "URL",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer HASHKEY');},
success: function() { alert('Success!'); }
});
or
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "URL", true);
xhttp.setRequestHeader("Authorization", "Bearer HASHKEY");
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function () {
var response = xhttp.responseText;
if (xhttp.readyState == 4 && xhttp.readyState == 200) {
var obj = JSON.parse(response);
// handle data as needed...
alert("obj" +obj);
}
};
Totally speaking I'm looking for a piece of code which can call API from the HTML which is content header: authorization.
Cheers
Try this:
$.ajax({
url: "URL",
type: "GET",
‎headers: {
‎"Authorization": "Bearer HASHKEY"
‎},
success: function() { alert('Success!'); }
});
Also, check that your server configuration supports CORS and explicitly allows the Authorization header.