'Salesforce - SharePoint File Upload 400 Bad Request Error
I am trying to upload file from Apex to Sharepoint but getting error as '400 Bad Request'.But work from JS CODE. Following is my code snippet :
- Apex Code
Http http = new Http();
HttpRequest httpRequestToSend = new HttpRequest();
httpRequestToSend.setEndpoint('https://sample.sharepoint.com/sites/siteName/_api/web/GetFolderByServerRelativeUrl(\''+'/sites/siteName/Shared Documents'+'\')/Files/Add(url=\''+'document3.txt'+'\', overwrite=true)');
httpRequestToSend.setMethod('POST');
httpRequestToSend.setHeader('Authorization', 'Bearer ' + token);
httpRequestToSend.setHeader('Content-Type','application/json; odata=verbose');
httpRequestToSend.setBodyAsBlob(Blob.ValueOf('test Message'));
System.debug('***** httpRequestToSend-->' + httpRequestToSend);
Http http1 = new Http();
HttpResponse httpResponse1 = http1.send(httpRequestToSend);
System.debug('***** httpResponse-->' + httpResponse1.toString());
System.debug(httpResponse1.getBody());
- JS CODE
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + Token);
myHeaders.append("Content-Type", "application/json;odata=verbose");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: fileBuffer,
};
fetch('https://sample.sharepoint.com/sites/siteName/_api/web/GetFolderByServerRelativeUrl(\'/sites/siteName/Shared Documents\')/Files/Add(url=\'test.txt\', overwrite=true)', requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => alert('error', error));
}
Thankyou
Solution 1:[1]
As per the documentation salesforce can't communicate to FTP directly that means can't Read/Write file at FTP Server.
I also faced this issue and this is how I resolved it:-
Step1: Create & host an External API on in any language(C#, Python) that takes two parameters one as fileName and the other one as fileData and uploads that file.
Step2: At Salesforce end, consume that API using HttpRequest and pass your file as filedata and fileName.
public void uploadFileToFTP_Service(string fileName,string fileData)
{
string value='{"fileName":"'+fileName+'","fileData": "'+fileData+'"}';
HttpRequest req = new HttpRequest();
req.setEndpoint('http://yourhostedApIPath:9001/data');
req.setMethod('POST');
req.setTimeout(120000);
req.setHeader('content-type','application/json; charset=utf-8');
req.setBody(value);
Http http = new Http();
HttpResponse res = http.send(req);
system.debug('Status code: ' + res.getStatusCode());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vermajai1995 |
