Unable to upload new file (<4MB) to SharePoint (ms graph api) - microsoft-graph-api

I'm trying to upload an attachment i get from Outlook to a folder inside a SharePoint document library.
I am Following the docs:
https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http#http-request-to-upload-a-new-file
fetch(`https://graph.microsoft.com/v1.0/sites/${siteId}/drive/items/${parentId}:/${attachment.name}:/content`, {
method: 'PUT',
mode: 'cors',
headers: new Headers({
'Authorization': `Bearer ${accesToken}`,
'Content-Type': 'text/plain'
}),
body: attachment.contentBytes
})
All I get is an error with code: -1, Microsoft.SharePoint.Client.InvalidClientQueryException
I've tried setting the body of the fetch request as a simple string such as "hello world" with testing purposes and still get the same error.
Any ideas?
Thx in advance
[EDIT]
I suspect I'm not building the URL right.
I haven't found the documentation for the parameter:
{item-id} I'm assuming this ID is the folder's parentReference.siteId attribute.
Is that right?

Allright, so after some testing with the Microsoft Graph Explorer, I've found that the easiest way to upload a file to a SharePoint folder living inside a document library (distinct to the root document library) is to deal with it as a drive using the endpoint:
/drives/{drive-id}/items/{parent-id}:/{filename}:/content
(https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http#http-request-to-upload-a-new-file)
In order to get the document library's drive-id, you can append to the graph query the odata parameter $expand=drive like:
`https://graph.microsoft.com/v1.0/sites/${siteId}/lists?$expand=drive`
Then, alongside other attributes of the targetted document library, you will find the "drive" object, which holds the drive-id associated to the document library you want to upload the file to. So, you would make the PUT request like:
fetch(`https://graph.microsoft.com/v1.0/drives/${libraryDriveId}/items/root:/${folderDisplayName}/${nameOfFile}:/content`, {
method: 'PUT',
mode: 'cors',
headers: new Headers({
'Authorization': `Bearer ${accesToken}`,
'Content-Type': 'text/plain'
}),
body: BINARY_STREAM_OF_DATA
}).then( (response) => {
if (!response.ok) return response.json().then((json) => {throw json});
return response.json();
}).then( (json) => {
//do whatever
}).catch( (err) => {
console.error(err);
})
libraryDriv
libraryDriveId comes from the https://graph.microsoft.com/v1.0/sites/${siteId}/lists?$expand=drive request
/root:/${folderDisplayName} means that the folder you are targetting inside the document library lives under "root:" (the root of the document library) followed by the displayName of the folder you want to upload the file to
nameOfFile is the name of the file you want to upload

Related

Autodesk-forge viewer: Access token

I was following forge tutorials to embed the forge viewer in an html page.
I ended up at this forge-made page, link: https://autodesk-forge.github.io/forge-tutorial-postman/display_svf.html
I understand how to retrieve an access token using cURL however I would like to modify that website so that I don't have to enter the access token myself.
I would like the access-token from the cURL response to be automatically imported as the access token for that website. How is this possible.
The code for the webpage is here: https://github.com/Autodesk-Forge/forge-tutorial-postman/blob/master/docs/display_svf.html
How can I add a function/method to automatically retrieve an access token when I hit submit on the webpage.
Any help is much appeciated!
Cheers!
The server side code you are looking for is:
app.get('/api/forge/oauth', function (req, res) {
Axios({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
data: querystring.stringify({
client_id: FORGE_CLIENT_ID,
client_secret: FORGE_CLIENT_SECRET,
grant_type: 'client_credentials',
scope: scopes
})
})
.then(function (response) {
// Success
access_token = response.data.access_token;
console.log(response);
res.send('<p>Authentication success!</p>');
})
.catch(function (error) {
// Failed
console.log(error);
res.send('Failed to authenticate');
});
});
Please refer the Forge 2-Legged Authentication tutorials for the code and more details. We also have more tutorials and workflow on Learn Autodesk Forge.

Edit yammer comment using REST Api

When using "https://api.yammer.com/api/v1/messages/", I get errors.First "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." error. Second CORS policy blocker error.
function editComment(MessagePostId,GroupID) {
var commentData = new FormData();
commentData.append('body', editedComment); //updated comment text
commentData.append('group_id', GroupID); //group id
commentData.append('replied_to_id', MessagePostId); Individual message id
yam.platform.request({
url: "https://api.yammer.com/api/v1/messages/"+MessagePostId,
method: "PATCH",
data: commentData,
success: function (res) {
alert("The request was successful.");
console.dir(res);
},
error: function (res) {
alert("There was an error with the request.");
console.log(res)
}
})}
I tried "POST" as well but facing the same issue again and again.
By any chance, is there any information about REST api for edit comments functionality ?.
Editing is not currently supported by the public API. This is noted in the original release announcement:
The endpoints will continue to get the most recent version of each
message. The data will not include version history or the edit flag.
There will not be endpoints for making edits to messages.

React-Native FormData File Requests being sent to the server as [object Object]

I am currently using React Native 0.48 and react-native-image-crop-picker 0.16.
I'm attempting to take a file uri, and send it to a server using FormData and Fetch.
Here is a code snippet of what I am doing:
var image = await ImagePicker.openPicker({
width: 500,
height: 500,
cropping: true,
includeBase64: true,
});
var media = {
uri: image.path,
type: 'image/jpeg',
name: 'file.jpg',
};
var formData = new FormData();
formData.append("file", media);
fetch("https://requestb.in/1e6lgdo1", {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
}).then(function(r){
console.log("Success", r);
}).catch(function(e){
console.log("Error", e);
}).done();
Unfortunately when the request gets sent to the server instead of sending the file contents in the "file" form data field, it's just sending "[Object object]".
Depending on where you send the request to, that either results in the file contents becoming "[object Object]" or the request erring out.
I am unable to determine if this is a problem with my own code, or with react native itself. Any assistance would be greatly appreciated.
Update
I am using https://github.com/jpillora/uploader for my test server. (Note: Go doesn't ever use the notation [object Object] when stringifying an object, so I do not believe the problem lies with the server. In addition I saw this when uploading a file to S3 as well.)
An example of a request that ends up getting sent out is:
------WebKitFormBoundaryzt2jTR8Oh7dXB56z
Content-Disposition: form-data; name="file"
[object Object]
------WebKitFormBoundaryzt2jTR8Oh7dXB56z--
This problem had to do with another package React-Native Debugger hijacking fetch requests in order to allow for inspection in the debugger.
Complete information on the workaround can be found here: https://github.com/jhen0409/react-native-debugger/issues/101
I was able to successfully bypass it however by going back to the Google Chrome debugger.

Having trouble deleting PFFile in Parse using opensource parse-server

I have a collection that has references to images, and when the user updates that collection with new images, I want to delete the old images. I am keeping references to the URL for the old images to pass into a function that is written in the cloud code.
I am running all of this local on my computer, however I get the same issue when I run this with the server running on Heroku. This is being called from the iOS SDK.
Here is the function in question:
Parse.Cloud.define('removeOldFilesFromDB', function (request, response) {
var fileUrls = request.params.fileUrls;
var promises = [];
for (var a = 0; a < fileUrls.length; a++) {
promises.push(Parse.Cloud.httpRequest({
method: 'DELETE',
url: fileUrls[a],
headers: {
'X-Parse-Application-Id': process.env.APP_ID || 'myAppId',
'X-Parse-Master-Key': process.env.MASTER_KEY || 'myMasterKey'
}
}));
}
Parse.Promise.when(promises).then( function (result) {
console.log("Successfully deleted files");
response.success(result);
}, function(a,b,c,d,e) {
console.log("Nope jacked it up!");
response.error("Error deleting files");
});
})
When I call the code in question, I don't even see the DELETE request in the parse-server logs at all.
I have the verbose: true flag set in my config, and this is the verbose output to the logs that I get when making this call from the client:
verbose: POST /parse/functions/removeOldFilesFromDB { host: 'e0ae0682.ngrok.io',
'x-parse-client-version': 'i1.12.0',
accept: '*/*',
'x-parse-session-token': 'r:5290c76c47678213770765d990ee38b6',
'x-parse-application-id': 'myAppId',
'x-parse-client-key': 'myClientKey',
'x-parse-installation-id': '3fafc219-1c63-4d68-b42f-5caa3e1c27cb',
'accept-language': 'en-us',
'accept-encoding': 'gzip, deflate',
'x-parse-os-version': '8.1 (12B411)',
'content-type': 'application/json; charset=utf-8',
'content-length': '204',
'user-agent': 'Spin%20the%20Bottle/1 CFNetwork/711.1.12 Darwin/14.0.0',
'x-parse-app-build-version': '1',
'x-parse-app-display-version': '1.0',
'x-forwarded-for': '71.163.238.223' } {
"fileUrls": [
"http://e0ae0682.ngrok.io/parse/files/myAppId/7b5b50e2871af27971be0425f367ab96_file.bin",
"http://e0ae0682.ngrok.io/parse/files/myAppId/cff909602b60b15331b1ac60a4f08697_file.bin"
]
}
Nope jacked it up!
verbose: error: code=141, message=Error deleting files
So it's odd that the DELETE call is not even showing up in there. Am I calling it wrong with the Parse.Cloud.httpRequest method or something?
If I hit the values for fileUrl in my browser, it downloads the images I'm trying to delete so the path is correct.
This is on the latest released version of parse-server, 2.2.10.
These were the instructions that I was following thinking that this is the correct way to do this:
https://parse.com/docs/rest/guide/#files-deleting-files
And this here to make the rest call from the cloud code:
https://parse.com/questions/making-a-rest-call-from-within-cloud-code
According to that, it says I can use Parse.Cloud.httpRequest to make REST calls, so I am not sure what you are referring to as that not the correct ways. Both of those have links to the docs and that is what I followed.
So I am obviously doing something wrong but I am not sure, anyone able to help out?
Just remove myAppId from file URL.
(e.g.)
from
http://e0ae0682.ngrok.io/parse/files/myAppId/7b5b50e2871af27971be0425f367ab96_file.bin
to
http://e0ae0682.ngrok.io/parse/files/7b5b50e2871af27971be0425f367ab96_file.bin

Download ZIP file in react-native

I'm writing an app using react-native and I will build it for both android and iOS.
Anyway, I have been trying to download a ZIP-file using react-native but I can't get it to work. After I have downloaded the file my plan is to unzip it and then store it using AsyncStorage.
But I keep getting the error below:
[RCTNetworking.m:330] Received data was not a string, or was not a recognised encoding.
I have tried various settings for my request but I guess I am simply missing something, the code currently looks like:
fetch('somewhere.path/file.zip', {
method: 'GET',
headers: {
'Accept-Encoding': 'application/zip'
},
})
.then((response) => {
console.log("Success");
})
.catch((error) => {
console.log("Error");
}).done();
Success gets printed but the response data does not contain the zip files data.
If it helps I am debugging using XCode and the simulator.
If anybody has any ideas please help me out! :)
Thanks in advance,
Yon
I also write an app to download some zip files and unzip it. And for download function, I using a plugin called react-native-fetch-blob. Code example:
import RNFetchBlob from 'react-native-fetch-blob';
...
RNFetchBlob.config({
fileCache : true,
path: path + '/file.zip'})
.fetch('GET','http://domain/file.zip')
.progress((received, total) => {console.log('progress', received / total)})
.then((res) => {// the temp file path
console.log('The file saved to ', res.path());
});
...
Thanks,

Resources